Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come posso valutare questa tabella?

ecco un esempio di codice che spiega come utilizzare un'istruzione CASE, dovresti essere in grado di capire come apportare le modifiche al tuo codice

--sample data
create table #temp (SomeDate datetime)
insert #temp values ( '2009-05-12 11:13:19.667')
insert #temp values ( '2009-05-12 11:12:19.667')
insert #temp values ( '2009-05-12 11:33:19.667')
insert #temp values ( '2009-05-12 11:43:19.667')
insert #temp values ( '2009-05-12 11:03:19.667')
insert #temp values ( '2009-05-12 11:53:19.667')
insert #temp values ( '2009-05-12 11:53:19.667')
insert #temp values ( '2009-05-12 11:23:19.667')

insert #temp values ( '2009-05-12 12:13:19.667')
insert #temp values ( '2009-05-12 12:12:19.667')
insert #temp values ( '2009-05-12 13:33:19.667')
insert #temp values ( '2009-05-12 13:43:19.667')
insert #temp values ( '2009-05-12 14:03:19.667')
insert #temp values ( '2009-05-12 14:53:19.667')
insert #temp values ( '2009-05-12 15:53:19.667')
insert #temp values ( '2009-05-12 15:23:19.667')



--this is the grouping/count query
select count(*),case when datepart(mi,Somedate) < 30 
then dateadd(hh, datediff(hh, 0, Somedate)+0, 0)
 else dateadd(mi,30,dateadd(hh, datediff(hh, 0, Somedate)+0, 0)) end
from #temp
group by case when datepart(mi,Somedate) < 30 
then dateadd(hh, datediff(hh, 0, Somedate)+0, 0)
 else dateadd(mi,30,dateadd(hh, datediff(hh, 0, Somedate)+0, 0)) end

per vedere come sono effettivamente i dati

select Somedate,case when datepart(mi,Somedate) < 30 
then dateadd(hh, datediff(hh, 0, Somedate)+0, 0)
 else dateadd(mi,30,dateadd(hh, datediff(hh, 0, Somedate)+0, 0)) end
from #temp

uscita

vCount  time
4   2009-05-12 11:00:00.000
4   2009-05-12 11:30:00.000
2   2009-05-12 12:00:00.000
2   2009-05-12 13:30:00.000
1   2009-05-12 14:00:00.000
1   2009-05-12 14:30:00.000
1   2009-05-12 15:00:00.000
1   2009-05-12 15:30:00.000