我正在使用SQL Server。当我尝试使用datepart函数按周对信息进行排序时,它不返回任何值。我的表格中有所选日期范围的值。
我尝试使用的查询是:
Declare @StartDate datetime, @EndDate datetime
set @StartDate = '20120401 00:00:00'
set @EndDate = '20120430 23:59:59'
;WITH
mytablePlusHours As
(
SELECT *,
DATEPART(ww, [eci_date]) AS [dateWeek]
FROM [mytable]
)
, mytableHourGroups As
(
SELECT dateWeek,
[eci_country],
COUNT(*) As [Number_Country],
ROW_NUMBER() OVER(PARTITION BY dateWeek ORDER BY [eci_country])
As [Country_Rank]
FROM mytablePlusHours
GROUP BY dateWeek, [eci_country]
)
SELECT
dateWeek AS [eci_date],
[eci_country],
[Number_Country]
FROM mytableHourGroups WITH(NOLOCK)
WHERE [dateWeek] between @StartDate and @EndDate
ORDER BY [dateWeek], [Number_Country] DESC
我可以在白天提取信息,但我无法弄清楚如何按周分类。有人可以告诉我我的代码在哪里错了吗?谢谢!
我正在尝试显示我的数据:
Week Country Count
16 United States 13
17 Canada 41
答案 0 :(得分:5)
[DateWeek]
不是日期,而是一个数字(1到53)。
要么...
将WHERE
子句移动到您的第一个CTE。
mytablePlusHours As
(
SELECT *, DATEPART(ww, [eci_date]) AS [dateWeek]
FROM [mytable]
WHERE [eci_date] between @StartDate and @EndDate
)
或者,将DATEPART()
更改为返回日期的函数...
mytablePlusHours As
(
SELECT *, DATEADD(WEEK, DATEDIFF(WEEK, 0, [eci_date]), 0) AS [dateWeek]
FROM [mytable]
)
答案 1 :(得分:4)
您将整数与日期进行比较。
DATEPART(ww...)
返回数字周(即一年中第三周的3周)。您的比较为datetime
,无法直接比较。
您需要与日期的周比较,您还应该检查年份。要检查一周:
WHERE [dateWeek] between DATEPART(ww,@StartDate) and DATEPART(ww,@EndDate)
您应该将年份添加到您的CTE并进行比较,否则1/15/2012和1/9/2011将同时显示在同一个“周”中。