简体   繁体   中英

SQL Server - Sorting by datepart week

I am using SQL Server. When I try to sort information by week using the datepart function it returns no values. 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).

Either...

Move the WHERE clause to your first 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...

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). Your comparisons are datetime which is not directly comparable.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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