【发布时间】:2019-11-19 19:50:00
【问题描述】:
我试图找到所有Cust 在 2018 年每个月至少有一天的会员资格。
我想出了在每个月的月初/中/月底检查他们的会员资格的解决方案,就像下面的 sn-p 一样,但试图找到更智能的解决方案。
我知道我可以在 365 天中的每一天使用计数表来检查这一点,但可能有更优雅的解决方案?我对 SQL 有点陌生,我想我在GROUPing 区域缺少一些东西。
在下面显示的代码 sn-p 中,Cust 都至少有一天的会员资格。
期望的输出:
CustID
------
1
22
代码:
with data as
(
select *
from (values (1, 1, '2017-12-11', '2018-01-16'), (1, 22, '2018-01-28', '2018-03-9' ), (1, 333, '2018-03-1', '2018-12-31') , -- island
(22, 1, '2017-12-31', '2018-01-11'), (22, 2, '2017-2-11', '2019-12-31')) as t (CustID, ContractID, StartDD, EndDD) ---
)
select
isdate(startDD), isdate(EndDD)
from
data
), gaps as
(
select
*,
datediff(day, lag(EndDD, 1, StartDD) over (partition by CustID order by StartDD), StartDD) as BreakDD -- negative is island
from
data
)
select
*,
datepart(month,StartDD) mmS , datepart(month,EndDD) mmE
from
gaps
-- and was active any 1+ day during each of the 12 months in 2018 ????
where
1 = 1
/* and (cast('1/1/2018' as date) between StartDD and EndDD
or cast('1/15/2018' as date) between StartDD and EndDD
or cast('1/31/2018' as date) between StartDD and EndDD)
---- etc.. for each month
and ( cast('12/1/2018' as date) between StartDD and EndDD
or cast('12/15/2018' as date) between StartDD and EndDD
or cast('12/31/2018' as date) between StartDD and EndDD
)
*/
--select CustID, max(BreakDD) Max_Days
--from gaps
--group by CustID
【问题讨论】:
-
提供你的 DDL 和一些示例数据。
-
这是带有计数的版本:select distinct custID, datepart(month,dd) -- gaps.*, t.dd from gaps join ( select top 365 cast ( dateadd(day, row_number() over (order by (select 1)) -1 , '1-1-2018') as date) as dd from master..spt_values ) t on t.dd 在 StartDD 和 EndDD 之间
-
试试我的答案。希望对您有所帮助。
标签: sql-server tsql