gpt4 book ai didi

sql-server - T-SQL CASE/子查询

转载 作者:行者123 更新时间:2023-12-02 05:26:19 25 4
gpt4 key购买 nike

下面有一个基于日期返回结果的 T-SQL 查询

SELECT
SUM(CASE WHEN date ='2012-10-31' then Amount ELSE 0 END) AS [Amount],
SUM(CASE WHEN date ='2012-10-31' then Discount1 ELSE 0 END) AS [Discount 1],
SUM(CASE WHEN date ='2012-10-31' then Discount2 ELSE 0 END) AS [Discount 2]
SUM(CASE WHEN date ='2012-10-31' then Amount - Discount1 - Discount2 ELSE 0 END) AS
[Total Amount]
FROM
Orders

当前结果:

Amount   Discount1   Discount2   Total
--------------------------------------
100.00 5.00 5.00 90.00

我想按月运行和显示/分组。有什么想法吗?

                         Amount    Discount1  Discount2   Total
-------------------------------------------
October 100.00 5.00 5.00 90.00
November 100.00 10.00 5.00 85.00
December 200.00 20.00 10.00 170.00

最佳答案

如果你需要按月分组,你可以试试类似这样:

select datename(mm, date) month,
sum(amount) amount,
sum(discount1) discount1,
sum(discount2) discount2,
sum(amount - discount1 - discount2) Total
from orders
group by datename(mm, date)

参见 SQL Fiddle with Demo

关于sql-server - T-SQL CASE/子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13037575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com