我有一个简单的表格,代表客户编号和购买时间。我需要知道任何特定客户何时在连续日期进行购买以及这些日期是什么。连续日期的数量无关紧要。
所以在这个例子中
+----------+--------+ | Customer | Date | +----------+--------+ | 123 | 21-Jan | | 123 | 24-Jan | | 345 | 21-Jan | | 345 | 23-Jan | | 345 | 24-Jan | | 123 | 26-Jan | | 123 | 27-Jan | +----------+--------+
我需要返回以下内容:
+----------+--------+ | Customer | Date | +----------+--------+ | 123 | 26-Jan | | 123 | 27-Jan | | 345 | 23-Jan | | 345 | 24-Jan | +----------+--------+
答案 0 :(得分:0)
尝试类似
的内容SELECT DISTINCT Customer , [Date]
FROM Table T
WHERE
Exists( SELECT 1 FROM Table WHERE [Date] = DATEADD(day,1,T.Date) OR [Date] = DATEADD(day, -1,T.Date))
如果日期包含时间,您需要正确格式化日期
答案 1 :(得分:0)
这是修改后的空白和岛屿问题。一种解决方案是使用ROW_NUMBER
:
WITH Cte AS(
SELECT *,
grp = DATEADD(DAY, -ROW_NUMBER() OVER(PARTITION BY Customer ORDER BY Date), Date)
FROM tbl
),
CteFinal AS(
SELECT *,
cnt = COUNT(Customer) OVER(PARTITION BY Customer, grp)
FROM Cte
)
SELECT
Customer, Date
FROM CteFinal
WHERE cnt > 1