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

klh5stk1  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(296)

假设我有下表:

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)。
将此操作应用于上表将产生:

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>

在SQLServer2008R2中执行的t-sql将实现这一点?

yftpprvb

yftpprvb1#

我已更改查询)
请试试这个:

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
kokeuurv

kokeuurv2#

你在描述 lead() :

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

相关问题