sql语法用于制作日期范围

时间:2017-07-24 14:47:43

标签: sql-server tsql

我有一些客户,他们在某些日子里访问了我的网站,我想为客户提供在线和离线日期作为范围。我有这样的事情:

A , 2017-01-10
A , 2017-01-17
A , 2017-01-18
B , 2017-01-15
B , 2017-01-16
B , 2017-01-17
B , 2017-01-20
B , 2017-01-21

我想要这样的东西:

A , 2017-01-10 , 2017-01-10 , 1
A , 2017-01-10 , 2017-01-17 , 0
A , 2017-01-17 , 2017-01-18 , 1
B , 2017-01-15, 2017-01-17, 1
B , 2017-01-17, 2017-01-20, 0
B , 2017-01-20, 2017-01-21, 1
你会帮我吗?

1 个答案:

答案 0 :(得分:0)

正如评论中的社群所说:提供的信息确实很少,而且客户“B”的日期2017-01-16缺失; - )

然而,这里有一些示例代码,您可能会如何获得类似的报告:

CREATE TABLE VISITS
(
 Customer varchar(10)
,DateVisit datetime
)

INSERT INTO VISITS VALUES
 ('A' , '20170110')
,('A' , '20170117')
,('A' , '20170118')
,('B' , '20170115')
,('B' , '20170116')
,('B' , '20170117')
,('B' , '20170120')
,('B' , '20170121')


;WITH cte as (
SELECT Customer, DateVisit, LAG(DateVisit,1,NULL) OVER (PARTITION BY Customer ORDER BY DateVisit) AS Last_DateVisit
FROM VISITS
)
SELECT 
 Customer
,DateVisit as OnlineDate
,Last_DateVisit as LastOnlineDate
,CASE WHEN a.Last_DateVisit IS NULL
     THEN 'First Visit ever :-)'
     ELSE cast(DATEDIFF(DAY,Last_DateVisit, DateVisit) as varchar) + ' Days since LastVisit'
     END AS Note
FROM cte as a

-- your sql server version does not support lag? try this:
;WITH cte as (
SELECT Customer, DateVisit,ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY DateVisit) as RowN
FROM VISITS
)
SELECT 
 a.Customer
,a.DateVisit as OnlineDate
,b.DateVisit as LastOnlineDate
,CASE WHEN b.DateVisit IS NULL
     THEN 'First Visit ever :-)'
     ELSE cast(DATEDIFF(DAY,b.DateVisit, a.DateVisit) as varchar) + ' Days since LastVisit'
     END AS Note
FROM cte as a
LEFT OUTER JOIN cte as b
on a.Customer = b.Customer
and a.RowN = b.RowN+1

输出

Customer | OnlineDate | LastOnlineDate | Note
---------+------------+----------------+-----------------------
A        | 2017-01-10 | NULL           | First Visit ever :-)
A        | 2017-01-17 | 2017-01-10     | 7 Days since LastVisit
A        | 2017-01-18 | 2017-01-17     | 1 Days since LastVisit
B        | 2017-01-15 | NULL           | First Visit ever :-)
B        | 2017-01-16 | 2017-01-15     | 1 Days since LastVisit
B        | 2017-01-17 | 2017-01-16     | 1 Days since LastVisit
B        | 2017-01-20 | 2017-01-17     | 3 Days since LastVisit
B        | 2017-01-21 | 2017-01-20     | 1 Days since LastVisit

我希望这段代码能为您提供一些如何获得解决方案或提出问题的建议。

此致 TGR