10/03/2011 11/03/2011 12/03/2011 13/03/2011 14/03/2011 15/03/2011 QUERYRESULT a a a a a 14/03/2011 b b b 13/03/2011 c c c c 12/03/2011
因此,对于最近的连续日期块,请返回该特定块的最早日期,如“queryresult”列中所示。
我现在意识到我在我给出的例子中无意中转换了数据 对于源可以假设模式是:[ID] 1,2,3,...; [type] a,b,c ..; [日期]
我可以通过递归的CTE /窗口/排名功能看到一些东西,但无法弄明白。
答案 0 :(得分:2)
比我想象的更容易,不需要CTE或窗口/排名功能:
假设数据是
ID mydate pfo 1 12/03/2011 a 4 13/03/2011 a 6 14/03/2011 a 10 16/03/2011 a 2 12/03/2011 b 5 13/03/2011 b 8 15/03/2011 b 3 12/03/2011 c 7 14/03/2011 c 9 15/03/2011 c 11 16/03/2011 c
然后
SELECT MAX( n.mydate) ,n.pfo FROM testtable n LEFT OUTER JOIN testtable n2 ON n.pfo = n2.pfo AND DATEADD(D,-1,n.mydate) = n2.mydate WHERE n2.mydate IS NULL GROUP BY n.pfo
答案 1 :(得分:1)
;WITH data (type, date) AS (
SELECT 'a', CAST('20110310' AS datetime) UNION ALL
SELECT 'a', CAST('20110311' AS datetime) UNION ALL
SELECT 'a', CAST('20110312' AS datetime) UNION ALL
SELECT 'a', CAST('20110314' AS datetime) UNION ALL
SELECT 'a', CAST('20110315' AS datetime) UNION ALL
SELECT 'b', CAST('20110313' AS datetime) UNION ALL
SELECT 'b', CAST('20110314' AS datetime) UNION ALL
SELECT 'b', CAST('20110315' AS datetime) UNION ALL
SELECT 'c', CAST('20110310' AS datetime) UNION ALL
SELECT 'c', CAST('20110312' AS datetime) UNION ALL
SELECT 'c', CAST('20110313' AS datetime) UNION ALL
SELECT 'c', CAST('20110314' AS datetime)
),
grouped AS (
SELECT
type,
date,
groupID = DATEADD(day, -ROW_NUMBER() OVER (PARTITION BY type ORDER BY date), date)
FROM data
),
startdates AS (
SELECT
type,
groupStartDate = MIN(date)
FROM grouped
GROUP BY type, groupID
)
SELECT
type,
LastGroupStartDate = MAX(groupStartDate)
FROM startdates
GROUP BY type