2

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

Current Output

Expected Output

Expected Output

Hardik Parmar
  • 1,053
  • 3
  • 15
  • 39

2 Answers2

8

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
Fahmi
  • 37,315
  • 5
  • 22
  • 31
1

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;
Alfonso Tienda
  • 3,442
  • 1
  • 19
  • 34