基于SQL Server中分区的Min()和Max()

时间:2019-08-19 12:05:55

标签: sql sql-server max min

我想在某些条件下使用最小和最大函数。

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')

带输出的当前查询

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

当前输出

Current Output

预期产量

Expected Output

2 个答案:

答案 0 :(得分:6)

您可以在下面尝试-这是一个间隙和孤岛的问题

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

输出:

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

答案 1 :(得分:1)

对于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;