create table #Events
(
EventID int identity primary key,
StartDate datetime not null,
EndDate datetime not null
)
go
insert into #Events (StartDate, EndDate)
select '2007-01-01 12:44:12 AM', '2007-01-01 12:45:34 AM' union all
select '2007-01-01 12:45:12 AM', '2007-01-01 12:46:34 AM' union all
select '2007-01-01 12:46:12 AM', '2007-01-01 12:47:34 AM' union all
select '2007-01-02 5:01:08 AM', '2007-01-02 5:05:37 AM' union all
select '2007-01-02 5:50:08 AM', '2007-01-02 5:55:59 AM' union all
select '2007-01-03 4:34:12 AM', '2007-01-03 4:55:18 AM' union all
select '2007-01-07 3:12:23 AM', '2007-01-07 3:52:25 AM'
( http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server をベースSQLの収集に対して謝罪します)
1時間以内に発生したイベントの数を見つけようとしているため、結果セットは次のようになります。
2007-01-01 12:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
私はdateaddとラウンドとグループ化で遊んでいますが、それを取得していません。誰でも助けることができますか?
ありがとう。
これはどう? SQL Server 2008の場合:
SELECT CAST(StartDate as date) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
2008年以前:
SELECT DATEADD(day,datediff(day,0,StartDate),0) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
この結果:
ForDate | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000 12 3
または、単にGROUP BY
時間と日:
SELECT CAST(Startdate as DATE) as 'StartDate',
CAST(DATEPART(Hour, StartDate) as varchar) + ':00' as 'Hour',
COUNT(*) as 'Ct'
FROM #Events
GROUP BY CAST(Startdate as DATE), DATEPART(Hour, StartDate)
ORDER BY CAST(Startdate as DATE) ASC
出力:
StartDate Hour Ct
2007-01-01 0:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
これはどこかで見つけました。私はこの答えが好きです!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]
また、同じ列の日付と時間、適切な日付時刻形式、および日付時刻順に並べられた次のSQLを使用してこれを実現することもできます
SELECT dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate',
COUNT(*) as 'Count'
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate