代码之家  ›  专栏  ›  技术社区  ›  Development 4.0

在Sql(postgres)中如何同时拥有两个聚合列

  •  1
  • Development 4.0  · 技术社区  · 7 年前

    我在邮局有一张桌子:

    ----------------------------------------------
    | 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
    

    我可以很容易地使用GROUPBY子句得到“月和”。 但我对如何显示第二列感到困惑。

    有人有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    你需要一个累加的总和,像这样:

    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), () );
    
    推荐文章