我有一个存储客户交易数据的交易表,如下表所示。
ID CustomerID Transaction Date
1 C001 01/07/2017
2 C001 01/07/2017
3 C001 01/07/2017
4 C001 02/07/2017
5 C002 02/07/2017
6 C001 15/07/2017
7 C001 15/07/2017
8 C001 16/07/2017
9 C001 17/07/2017
我想从连续2天的交易中选择customerId的计数与月份相同。就像 01/07/2017至02/07/2017,02/07/2017至03之间的客户选择计数一样/ 07/2017 等。
结果应该是这样的。
count CustomerID fromDate toDate
4 C001 01/07/2017 02/07/2017
3 C001 15/07/2017 16/07/2017
2 C001 16/07/2017 17/07/2017
1 C001 17/07/2017 18/07/2017
编辑:可用的样本数据:
CREATE TABLE #Sample (ID int, CustomerID char(4), TransactionDate Date);
GO
INSERT INTO #Sample
VALUES
(1,'C001','20170701'),
(2,'C001','20170701'),
(3,'C001','20170701'),
(4,'C001','20170702'),
(5,'C002','20170702'),
(6,'C001','20170715'),
(7,'C001','20170715'),
(8,'C001','20170716'),
(9,'C001','20170717');
--DROP TABLE #Sample;
答案 0 :(得分:1)
我可以接近你的要求
实际上,您所需的输出存在问题 请考虑ID = 5案例和ID = 9案例
; with cte as (
select
distinct
CustomerId,
PrevDate = dateadd(dd,-1,TransactionDate),
TransactionDate,
NextDate = dateadd(dd,1,TransactionDate)
from #Sample
)
select
customerId, TransactionDate, NextDate,
(
select count(*)
from #Sample t
where
t.customerId = cte.customerId and
t.TransactionDate between cte.TransactionDate and cte.NextDate
) as cnt
from cte
where
(
exists (select * from cte as t2 where t2.customerId = cte.customerId and t2.TransactionDate = cte.NextDate)
)
or
(
not exists (select * from cte as t2 where t2.customerId = cte.customerId and t2.TransactionDate = cte.NextDate)
and
not exists (select * from cte as t2 where t2.customerId = cte.customerId and t2.TransactionDate = cte.PrevDate)
)
order by customerId, TransactionDate
答案 1 :(得分:0)
您可以使用lead()
:
select customerid, tdate as from_date, next_tdate as to_date
from (select t.*, lead(tdate) over (partition by customerId order by tdate) as next_tdate
from (select distinct customerId, tdate
from transactions t
) t
) t
where next_tdate is not null;