SQL DATEPART(dw,date) need monday = 1 and sunday = 7

后端 未结 12 567
[愿得一人]
[愿得一人] 2020-12-23 16:27

I have a Query where I get the WeekDay of a date but by default:

  • Sunday = 1

  • Moday = 2

  • etc.

相关标签:
12条回答
  • 2020-12-23 17:12

    I think this could work:

      select
        case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
    
    0 讨论(0)
  • 2020-12-23 17:12

    I think

    DATEPART(dw,ads.date - 1) as weekday 
    

    would work.

    0 讨论(0)
  • 2020-12-23 17:13

    I would suggest that you just write the case statement yourself using datename():

    select (case datename(dw, aws.date)
                 when 'Monday' then 1
                 when 'Tuesday' then 2
                 when 'Wednesday' then 3
                 when 'Thursday' then 4
                 when 'Friday' then 5
                 when 'Saturday' then 6
                 when 'Sunday' then 7
            end)
    

    At least, this won't change if someone changes the parameter on the day of the week when weeks begin. On the other hand, it is susceptible to the language chosen for SQL Server.

    0 讨论(0)
  • 2020-12-23 17:17

    Try this:

    CREATE FUNCTION dbo.FnDAYSADDNOWK(
              @addDate AS DATE, 
              @numDays AS INT
           ) RETURNS DATETIME AS
    
        BEGIN
        WHILE @numDays > 0 BEGIN
            SET @addDate = DATEADD(day, 1, @addDate)    
            IF DATENAME(DW, @addDate) <> 'sunday' BEGIN
                SET @numDays = @numDays - 1 
            END
        END
    
        RETURN CAST(@addDate AS DATETIME)
    END
    
    0 讨论(0)
  • 2020-12-23 17:19

    This will do it.

    SET DATEFIRST 1;
    
    -- YOUR QUERY
    

    Examples

    -- Sunday is first day of week
    set datefirst 7; 
    select DATEPART(dw,getdate()) as weekday
    
    
    -- Monday is first day of week
    set datefirst 1;
    select DATEPART(dw,getdate()) as weekday
    
    0 讨论(0)
  • 2020-12-23 17:20

    You would need to set DATEFIRST. Take a look at this article. I believe this should help.

    https://docs.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql

    0 讨论(0)
提交回复
热议问题