SQL中的条件计算列
Posted
技术标签:
【中文标题】SQL中的条件计算列【英文标题】:Conditional Calculating Column in SQL 【发布时间】:2020-09-19 00:30:16 【问题描述】:我在 SQL 中有一个名为Invoice
的表。
InvNo Date CustName TypeOfSale Tax Grand
21 2019 AA T1 $1.00 $10.00
22 2019 AA T2 $2.00 $20.00
23 2019 BB T1 $1.00 $10.00
24 2020 AA T1 $1.00 $10.00
25 2020 BB T1 $1.00 $10.00
26 2020 BB T2 $2.00 $20.00
我正在尝试执行显示下表的查询
在reselut中,我正在寻找按年收入以及销售类型
如果我假设Revenue = Grand - Tax
那么:
CustName Revenue TypeT1 2019 Revenue TypeT2 2019 Revenue TypeT1 2020 Revenue TypeT2 2020
AA $9.00 $18.00 $9.00 $0.00
BB $9.00 $0.00 $9.00 $18.00
我真的很感谢任何帮助
【问题讨论】:
【参考方案1】:对于销售类型和年份的固定列表,您可以进行条件聚合:
select custname,
sum(case when date = 2019 and typeofsale = 'T1' then grand - tax else 0 end) t1_2019,
sum(case when date = 2019 and typeofsale = 'T2' then grand - tax else 0 end) t2_2019,
sum(case when date = 2020 and typeofsale = 'T1' then grand - tax else 0 end) t1_2020,
sum(case when date = 2020 and typeofsale = 'T2' then grand - tax else 0 end) t2_2020
from mytable
group by custname
【讨论】:
以上是关于SQL中的条件计算列的主要内容,如果未能解决你的问题,请参考以下文章