Как сложить конкретную колонку с месяцем и годом - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть следующие данные в моей таблице:

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

Как я могу это сделать?

1 Ответ

1 голос
/ 08 апреля 2020

Вы можете поворачиваться с условным агрегированием:

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