Max dates for each sequence within partitions

雨燕双飞 提交于 2019-12-24 18:53:25

问题


I would like to see if somebody has an idea how to get the max and min dates within each 'id' using the 'row_num' column as an indicator when the sequence starts/ends in SQL Server 2016.

The screenshot below shows the desired output in columns 'min_date' and 'max_date'.

Any help would be appreciated.


回答1:


Try something like

SELECT 
    Q1.id, Q1.cat, 
    MIN(Q1.date) AS min_dat, 
    MAX(Q1.date) AS max_dat 
FROM 
    (SELECT 
         *, 
         ROW_NUMBER() OVER (PARTITION BY id, cat ORDER BY [date]) AS r1, 
         ROW_NUMBER() OVER (PARTITION BY id ORDER BY [date]) AS r2
    ) AS Q1
GROUP BY 
    Q1.id, Q1.r2 - Q1.r1



回答2:


You could use windowed MIN/MAX:

WITH cte AS (
  SELECT *,SUM(CASE WHEN row_num > 1 THEN 0 ELSE 1 END) 
         OVER(PARTITION BY id, cat ORDER BY date_col) AS grp
  FROM tab
)
SELECT *, MIN(date_col) OVER(PARTITION BY id, cat, grp) AS min_date,
          MAX(date_col) OVER(PARTITION BY id, cat, grp) AS max_date
FROM cte
ORDER BY id, date_col, cat;

Rextester Demo



来源:https://stackoverflow.com/questions/52101614/max-dates-for-each-sequence-within-partitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!