我必须按小时对某人从特定国家/地区拨打电话的次数进行排序。国家列表按月增加,例如我们可以添加巴西。我正在使用 SQL Server。
数据看起来像这样
2012-04-02 08:00:59 United States
2012-04-02 08:12:02 United States
2012-04-02 08:13:42 Canada
2012-04-02 08:13:56 United States
2012-04-02 08:14:07 Mexico
2012-04-02 08:18:09 Canada
2012-04-02 08:19:50 United States
2012-04-02 08:34:34 Mexico
etc.
我想如何按小时列出前 2 个国家/地区的数据。
我希望它显示如下:
Date Country Calls
2012-04-02 08:00:00 United States 24
2012-04-02 08:00:00 Canada 19
--hidden--
2012-04-02 08:00:00 Mexico 12
我尝试的代码(不起作用):
Declare @StartDate datetime, @EndDate datetime
set @StartDate = '20120401 00:00:00'
set @EndDate = '20120430 23:59:59'
SELECT DATEADD(HOUR, DATEPART(HOUR, [date]), DATEDIFF(DAY, 0, [date])) as [date],
(SELECT COUNT([country]) FROM [mytable] WHERE [date] between @StartDate and @EndDate and [country] = 'United States' ) as [United_States]
,(SELECT COUNT([country]) FROM [mytable] WHERE [date] between @StartDate and @EndDate and [country] = 'Canada' ) as [Canada]
,(SELECT COUNT([country]) FROM [mytable] WHERE [date] between @StartDate and @EndDate and [country] = 'Mexico' ) as [Canada]
FROM [mytable]
WHERE [date] between @StartDate and @EndDate
GROUP BY DATEADD(HOUR, DATEPART(HOUR, [date]), DATEDIFF(DAY, 0, [date]))
ORDER BY [date]
谢谢你。