【问题标题】:How to sum of particular column with month and year wise如何按月和年计算特定列的总和
【发布时间】:2020-07-20 15:00:26
【问题描述】:

我的表中有以下数据:

uniqueId    d_date      amount
1         2018-02-01    100.25
2         2019-03-01    456.5
3         2018-02-01    455
4         2019-05-01    200.48
5         2018-06-01    100
6         2019-07-01    200
7         2018-12-01    6950

现在我想要这样的输出:

Year   Jan  Feb     Mar    Apr  May      Jun  July  Aug Sept Oct Nov Dec     Total
2018    -   555.25   -      -   -        100   -     -   -    -   -  6950   7605.25
2019    -   -       456.5   -   200.48    -     200  -   -    -   -  -      856.98

我该怎么做?

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008 pivot


    【解决方案1】:

    您可以使用条件聚合进行透视:

    select
        year(d_date) yr,
        sum(case when month(d_date) = 1 then amount end) Jan,
        sum(case when month(d_date) = 2 then amount end) Feb,
        sum(case when month(d_date) = 3 then amount end) Mar,
        ...
        sum(case when month(d_date) = 12 then amount end) Dec,
        sum(amount) total
    from mytable
    group by year(d_date)
    order by yr
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 2013-08-29
      • 2020-12-28
      相关资源
      最近更新 更多