简体   繁体   English

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

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

Suppose I had the following 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

For each unique UserId/AttributeId pair, it is assumed that the DateEnd is the day prior to the next DateStart for that pair, otherwise it is null (or some default like crazy far into the future - 12/31/3000).对于每个唯一的 UserId/AttributeId 对,假定 DateEnd 是该对的下一个 DateStart 的前一天,否则它是 null (或一些默认的疯狂到未来 - 12/31/3000)。

Applying this operation to the above table would yield:将此操作应用于上表将产生:

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>

What T-SQL, executing in SQL Server 2008 R2, would accomplish this?什么 T-SQL,在 SQL Server 2008 R2 中执行,会完成这个?

I have changed query)我已更改查询)

Try this please:请试试这个:

  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

You are describing lead() :您正在描述lead()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM