DB2,按年份分组和求和,其中年份是列值
Posted
技术标签:
【中文标题】DB2,按年份分组和求和,其中年份是列值【英文标题】:DB2, group and sum by year where the year is a column value 【发布时间】:2021-05-12 17:14:11 【问题描述】:我目前有一个这样的 db2 查询:
SELECT
NUMBER ,
YEAR(newDate),
dollarAMT - CAST ( coupon * dollarAMT AS DECIMAL ( 12 , 2 ) ) AS TOTAL
FROM ORDERING A
LEFT JOIN table.clients CL ON CL . clientNUmber = A . clientNumber
WHERE
newDate >= '2019-01-01'
order by newDate asc;
这给出了这样的值:
123 2019 100.00
123 2019 200.00
123 2020 500.00
123 2020 800.00
123 2021 1000.00
我正在尝试得到这个结果:
Number 2019 2020 2021
123 300.00 1300.00 1000.00
如何在 DB2 中更改它,以便年份成为列名并按年份对销售额进行分组?
【问题讨论】:
【参考方案1】:您需要对数据进行透视,但 DB2 不支持 PIVOT,因此您可以执行以下操作:
select
number,
sum(case when YEAR(newDate) = 2019 then (dollarAMT - CAST ( coupon * dollarAMT AS DECIMAL ( 12 , 2 ) ) ) end) as 2019,
sum(case when YEAR(newDate) = 2020 then (dollarAMT - CAST ( coupon * dollarAMT AS DECIMAL ( 12 , 2 ) ) ) end) as 2020,
sum(case when YEAR(newDate) = 2021 then (dollarAMT - CAST ( coupon * dollarAMT AS DECIMAL ( 12 , 2 ) ) ) end) as 2021,
FROM ORDERING A
LEFT JOIN table.clients CL ON CL.clientNUmber = A.clientNumber
WHERE newDate >= '2019-01-01'
group by number
order by number asc;
但是如果您可以将它们显示在 rows 而不是 columns 中,它会使查询更加简单,并且不需要为即将到来的每一年进行修改:
SELECT
NUMBER,
YEAR(newDate),
sum(dollarAMT - CAST (coupon * dollarAMT AS DECIMAL (12, 2))) AS TOTAL
FROM ORDERING A
LEFT JOIN table.clients CL ON CL.clientNUmber = A.clientNumber
WHERE newDate >= '2019-01-01'
group by NUMBER, YEAR(newDate)
order by NUMBER, YEAR(newDate) asc;
【讨论】:
以上是关于DB2,按年份分组和求和,其中年份是列值的主要内容,如果未能解决你的问题,请参考以下文章