一尘不染

SQL:GROUP BY之后的SUM

sql

样品表

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是无用的

谢谢


阅读 219

收藏
2021-03-08

共1个答案

一尘不染

[sql fiddle demo](http://www.sqlfiddle.com/#!3/811a6/3/0)

此SQL Fiddle解决了您的疑虑。您需要生成一个Calendar表,以便您可以将日期添加到其中。然后,您可以为每个客户计算不同的MonthYears。

create table test(
  CustomerId int,
  StartDate date,
  EndDate date
  )

insert into test
values 
  (10, '9/1/2013', '9/30/2013'),
  (10, '9/1/2013', '9/30/2013'),
  (11, '9/1/2013', '11/30/2013'),
  (11, '9/1/2013', '11/30/2013'),
  (11, '9/1/2013', '11/30/2013'),
  (10, '10/1/2013', '12/31/2013'),
  (10, '10/1/2013', '12/31/2013'),
  (11, '12/1/2013', '4/30/2014')

create table calendar(
  MY varchar(10),
  StartDate date,
  EndDate date
  )

insert into calendar
values 
  ('9/2013', '9/1/2013', '9/30/2013'),
  ('10/2013', '10/1/2013', '10/31/2013'),
  ('11/2013', '11/1/2013', '11/30/2013'),
  ('12/2013', '12/1/2013', '12/31/2013'),
  ('1/2014', '1/1/2014', '1/31/2014'),
  ('2/2014', '2/1/2014', '2/28/2014'),
  ('3/2014', '3/1/2014', '3/31/2014'),
  ('4/2014', '4/1/2014', '4/30/2014')

select
  t.CustomerId, 
  count(distinct c.MY)
from
  test t
  inner join calendar c
    on t.StartDate <= c.EndDate
      and t.EndDate >= c.StartDate
group by
  t.CustomerId
2021-03-08