在SQL Server中连续两天选择客户计数

问题描述 投票:-2回答:2

我有一个存储客户交易数据的交易表,如下表所示。

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计数与月份相同。类似于客户的选择计数,日期为2017年7月1日至2017年2月2日,2017年7月2日至2017年3月3日等。

结果应该是这样的。

      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;
sql sql-server database
2个回答
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

enter image description here


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;
© www.soinside.com 2019 - 2024. All rights reserved.