gpt4 book ai didi

SQL:GROUP BY 之后的 SUM

转载 作者:行者123 更新时间:2023-12-04 02:43:37 25 4
gpt4 key购买 nike

示例表

CustomerId | VoucherId | CategoryId | StartDate | EndDate
-------------------------------------------------------------
10 | 1 | 1 | 2013-09-01| 2013-09-30
10 | 1 | 2 | 2013-09-01| 2013-09-30
11 | 2 | 1 | 2013-09-01| 2013-11-30
11 | 2 | 2 | 2013-09-01| 2013-11-30
11 | 2 | 3 | 2013-09-01| 2013-11-30
10 | 3 | 1 | 2013-10-01| 2013-12-31
10 | 3 | 2 | 2013-10-01| 2013-12-31
11 | 4 | 1 | 2013-12-01| 2014-04-30

在上面的示例记录中,我想找出客户凭证涵盖的总月数

我需要表单中的输出

CustomerId | Months
--------------------
10 | 4
11 | 8

要注意的是,一张凭证可以有多行表示不同的 CategoryIds...

我将凭证涵盖的月份计算为 DATEDIFF(MM, StartDate, EndDate) + 1...

当我申请 SUM(DATEDIFF(MM, StartDate, EndDate)) GROUP BY VoucherId, StartDate, EndDate由于 VoucherId 的多行,我给出了错误的结果....

我得到了这样的东西......

CustomerId | Months
--------------------
10 | 8
11 | 14

CategoryId 在这种情况下没用

谢谢

最佳答案

实际上,在您的情况下(当每个类别的时间段相等时)您可以使用此查询:

with cte as (
select distinct
CustomerId, StartDate, EndDate
from Table1
)
select CustomerId, sum(datediff(mm, StartDate, EndDate) + 1) as diff
from cte
group by CustomerId

sql fiddle demo

关于SQL:GROUP BY 之后的 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323353/

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