Dies ist eigentlich das geiche Skript welches ich bereits für Oracle gepostet habe, jedoch nun für MSSQL.
Auch hier verwende ich für die Übersicht eine function welche einfach prüft ob zwei Werte identisch sind:
use TEST if object_id(N'dbo.ds', N'FN') is not null drop function dbo.ds; go create function dbo.ds(@a int,@b int) returns int as -- Returns the stock level for the product. begin declare @ret int; set @ret = 0; if (@a=@b) set @ret = 1; return @ret; end;
Eine Testtabelle mit ein paar Einträgen (evt. liegt irgendwo bereits ein besseres Beispiel rum)
use TEST create table datum ( mydate datetime ) insert into datum(mydate) values(getdate()); go 100
Die eigentliche Abfrage bei welcher pro Datum (Tag) die Anzahl für den ganzen Tag und die Anzahl pro Stunde angezeigt werden.
use TEST select d as "datum",count(*) as "Count", sum(dbo.ds(h,00)) h00,sum(dbo.ds(h,01)) h01, sum(dbo.ds(h,02)) h02,sum(dbo.ds(h,03)) h03, sum(dbo.ds(h,04)) h04,sum(dbo.ds(h,05)) h05, sum(dbo.ds(h,06)) h06,sum(dbo.ds(h,07)) h07, sum(dbo.ds(h,08)) h08,sum(dbo.ds(h,09)) h09, sum(dbo.ds(h,10)) h10,sum(dbo.ds(h,11)) h11, sum(dbo.ds(h,12)) h12,sum(dbo.ds(h,13)) h13, sum(dbo.ds(h,14)) h14,sum(dbo.ds(h,15)) h15, sum(dbo.ds(h,16)) h16,sum(dbo.ds(h,17)) h17, sum(dbo.ds(h,18)) h18,sum(dbo.ds(h,19)) h19, sum(dbo.ds(h,20)) h20,sum(dbo.ds(h,21)) h21, sum(dbo.ds(h,22)) h22,sum(dbo.ds(h,23)) h23 from (select cast(datepart(year, mydate) as varchar)+'-'+ RIGHT(REPLICATE('0',2)+cast(datepart(month,mydate) as varchar),2)+'-'+ RIGHT(REPLICATE('0',2)+cast(datepart(day, mydate) as varchar),2) d, cast(datepart(hour,mydate) as varchar) h From datum) a group by d order by 1 desc;