t-sql 从平面日期列表中总结日期范围,按其他列分组

t-sql to summarize range of dates from flat list of dates, grouped by other columns

假设我有以下 table:

UserId   AttributeId   DateStart
1        3             1/1/2020
1        4             1/9/2020
1        3             2/2/2020
2        3             3/5/2020
2        3             4/1/2020
2        3             5/1/2020

对于每个唯一的 UserId/AttributeId 对,假设 DateEnd 是该对的下一个 DateStart 的前一天,否则它为 null(或者一些默认值,比如疯狂的未来 - 12/ 31/3000).

将此操作应用于上述 table 将产生:

UserId   AttributeId   DateStart     DateEnd
1        3             1/1/2020      2/1/2020
1        4             1/9/2020      <null>
1        3             2/2/2020      <null>
2        3             3/5/2020      3/31/2020
2        3             4/1/2020      4/30/2020
2        3             5/1/2020      <null>

什么 T-SQL,在 SQL Server 2008 R2 中执行,会完成这个?

您正在描述 lead():

select t.*,
       dateadd(day, -1, lead(dateStart) over (partition by userId, attributeId order by dateStart)) as dateEnd
from t;

我已更改查询)

请试试这个:

  SELECT 
  UserId,AttributeId,DateStart,Min(DateEnd)DateEnd
  FROM
  (
 
   SELECT X.UserId,X.AttributeId,X.DateStart, DATEADD(DD,-1,Y.DateStart) DateEnd
   FROM TAB X LEFT JOIN TAB Y
   ON (X.UserId=Y.UserId) AND (X.AttributeId=Y.AttributeId)
   AND   (X.DateStart<Y.DateStart) 

  )
 T
 GROUP BY UserId,AttributeId,DateStart
 ORDER BY DateStart