Min() and Max() based on partition in sql server

蹲街弑〆低调 提交于 2020-12-12 10:16:45

问题


I want to use min & max function but on certain criteria.

Create Table #Test (Id Int Identity(1,1), Category Varchar(100), DateTimeStamp DateTime)



    Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 01:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 02:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 03:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 04:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 05:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c2','2019-08-13 06:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c2','2019-08-13 07:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c2','2019-08-13 08:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c2','2019-08-13 09:00:13.503')
        Insert into #Test (Category,DateTimeStamp) values ('c2','2019-08-13 10:00:13.503')  
        Insert into #Test (Category,DateTimeStamp) values ('c1','2019-08-13 11:00:13.503')

Current Query With Output

select category, min(DateTimeStamp) as minn , max(DateTimeStamp) as maxx from #Test
group by category

Current Output

Expected Output


回答1:


You can try below - it's a gap & island problem

DEMO

select category, min(datetimestamp),max(datetimestamp)
from
(
select *,row_number() over(order by datetimestamp) -
row_number() over(partition by category order by datetimestamp) as rn2
from #Test
)A group by category,rn2 order by 2

OUTPUT:

category       minval               maxval
c1             13/08/2019 01:00:13  13/08/2019 05:00:13
c2             13/08/2019 06:00:13  13/08/2019 10:00:13
c1             13/08/2019 11:00:13  13/08/2019 11:00:13



回答2:


For postgres:

SELECT category, min(DateTimeStamp) as minn , max(DateTimeStamp) as maxx 
FROM (Select *,
      SUM(CASE WHEN Category <> PrevCategory THEN 1 ELSE 0 END)  OVER (ORDER BY 
      ID,Category,DateTimeStamp) As partition
      From (Select * ,LAG (Category, 1) OVER (ORDER BY ID) AS PrevCategory From Test)  As 
           help) As helper 
GROUP BY category,partition;


来源:https://stackoverflow.com/questions/57556389/min-and-max-based-on-partition-in-sql-server

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