样本表
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
问题在于,一张凭证可以有多行代表不同的 CategoryId...
我将优惠券涵盖的月份计算为 DATEDIFF(MM, StartDate, EndDate) + 1...
当我应用 SUM(DATEDIFF(MM, StartDate, EndDate)) GROUP BY VoucherId, StartDate, EndDate 时
由于 VoucherId 有多行,我给出了错误的结果......
我得到这样的东西......
CustomerId | Months
--------------------
10 | 8
11 | 14
CategoryId 在这种情况下没有用处
Thanks
实际上,在您的情况下(当每个类别的周期相等时)您可以使用以下查询:
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 http://sqlfiddle.com/#!3/dae90/9
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)