简体   繁体   中英

SQL query for group by date

SQL table in the below data format

Datetime           Type    Id  
6/18/2018 8:00:00   A      1  
6/18/2018 9:00:00   A      2  
6/18/2018 10:00:00  A      3  
6/18/2018 11:00:00  B      4
6/18/2018 12:30:00  B      5  
6/18/2018 13:15:00  A      6  
6/18/2018 14:00:00  A      7  

Result table needed

Type Startdate          Enddate            Count Changeovertime

A    6/18/2018 8:00:00  6/18/2018 10:00:00   3   NA  
B    6/18/2018 11:00:00  6/18/2018 12:30:00  2   1:00:00       
A    6/18/2018 13:15:00  6/18/2018 14:00:00  2   0:45:00  

Can you help me to get the query for the result?

I am using sql server 2008 express edition.

Regards Dilipan.

You can use difference of row_number() :

select Type, min(datetime) as startdate, max(datetime) as enddate, count(*) as count
from (select *, row_number() over (partition by type order by id) seq
      from table
     ) t
group by Type, (Id-Seq);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM