简体   繁体   English

SQL Server-按日期部分星期排序

[英]SQL Server - Sorting by datepart week

I am using SQL Server. 我正在使用SQL Server。 When I try to sort information by week using the datepart function it returns no values. 当我尝试使用datepart函数按周对信息进行排序时,它不返回任何值。 There are values in my table for the selected date range. 我的表格中有所选日期范围内的值。

The query I am trying to use is: 我要使用的查询是:

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

I can pull information by day but I cannot figure out how to sort it by week. 我可以按日提取信息,但无法弄清楚如何按周排序。 Can someone please advise me where my code is wrong? 有人可以告诉我我的代码哪里错误吗? Thanks! 谢谢!

I am trying to display my data like: 我正在尝试显示我的数据,例如:

Week Country       Count
16   United States  13
17   Canada         41

[DateWeek] isn't a date, it's a number (1 to 53). [DateWeek]不是日期,而是一个数字(1到53)。

Either... 要么...

Move the WHERE clause to your first CTE. WHERE子句移到第一个CTE。

mytablePlusHours As
(
  SELECT *, DATEPART(ww, [eci_date])     AS [dateWeek]
    FROM [mytable]
   WHERE [eci_date] between @StartDate and @EndDate
)

Or, change the DATEPART() to a function that returns a date... 或者,将DATEPART()更改为返回日期的函数。

mytablePlusHours As
(
  SELECT *, DATEADD(WEEK, DATEDIFF(WEEK, 0, [eci_date]), 0) AS [dateWeek]
    FROM [mytable]
)

You're comparing an integer to a date. 您正在将整数与日期进行比较。

DATEPART(ww...) returns the numerical week (ie 3 for the third week of the year). DATEPART(ww...)返回数字星期(即一年的第三周为3)。 Your comparisons are datetime which is not directly comparable. 您的比较是datetime ,不能直接比较。

You need to compare to the week of the dates, and you should also check the year. 您需要与日期中的星期进行比较,还应检查年份。 To check just the week: 要检查一周:

WHERE   [dateWeek] between  DATEPART(ww,@StartDate) and DATEPART(ww,@EndDate)

You should add year to your CTE and compare that as well, otherwise 1/15/2012 and 1/9/2011 will both show up in the same "week". 您应该在CTE中添加年份并进行比较,否则1/15/2012和1/9/2011都将显示在同一“周”中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM