【问题标题】:In Sql (postgres) how to have two aggregate columns at the same time在Sql(postgres)中如何同时拥有两个聚合列
【发布时间】:2018-10-31 15:46:16
【问题描述】:

我在 Postgres 中有一张桌子:

----------------------------------------------
| id | product| price| chain| location| date |           
----------------------------------------------

我需要显示为:

2018 年 9 月(每月)

         |  sum for the month |  sum for the year so far 
 ----------------------------------------------------------------
location  |          100       |      200
product1  |           1        |        2
product2  |           99       |      198
-----------------------------------------------------------------
Total     |          100       |      200
=================================================================

enter code here
enter code here

我可以很容易地通过使用 group by 子句来获得“月总和”。 但我对如何显示第二列感到困惑。

有人有什么想法吗?

【问题讨论】:

  • 使用case表达式进行条件聚合。
  • location 行项目与 Total 有何不同?另外,请在您发布的空白 Postgres 表中添加数据示例。
  • 您必须先将子查询合并在一起(按位置分组,产品合一),然后计算出滚动/累积总和。这最好留给演示工具,恕我直言。

标签: sql postgresql reporting


【解决方案1】:

你想要一个累积的总和,像这样:

select date_trunc('month', date) as yyyymm, sum(price),
       sum(sum(price)) over (partition by extract(year from date) order by min(date)) as ytd
from location
group by grouping sets ( (yyyymm), () );

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2020-09-04
    • 2016-03-13
    • 2017-08-22
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多