简体   繁体   中英

SQL: First day of week Monday

I would like to display Monday as the first day of the week and Sunday the last day of the week. I am using for this report the Report server.

my query:

   Select
Datum,
Sum(Prod) as Prod

FROM ( 
Select 

intervaldate as Datum,
Sum(case when TabName = 'Produzierte Dosen' then DisplayUnits else 0 end) as Prod


from vwOeeIntervalCount 
where 
IntervalDateWeek >=  dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)  
and IntervalDateWeek < dateadd(wk, datediff(wk, 0, getdate()), 0)
and  IntervalDate >= dateadd(day,datediff(day,0,GETDATE())-6,0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0) 

and CalculationName = 'Packaging'

group by intervaldate
)c

group by Datum

Here the result:

Date                      |Prod 
2018-02-25 00:00:00.000   |1836528
2018-02-26 00:00:00.000   |8131127,99999999

EDIT: Sorry here is my question. I would like to display the Monday as the first day of the week. My query displays the Sunday as the first day of the week. How can I do that?

By default MS SQL Server has configured sunday as first day of a week.

You can set the server config for the first day of a week to any day with the following command:

SET DATEFIRST { number | @number_var } 

Value   First day of the week is
1   Monday
2   Tuesday
3   Wednesday
4   Thursday
5   Friday
6   Saturday
7 (default, U.S. English)   Sunday

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

you can use this to the current week:

/*-- Week Start
--1->Sunday --2->Monday....*/
SELECT CAST(DATEADD(dd, -(DATEPART(dw,  GETDATE()))+2, GETDATE()) AS DATE) [WeekStart], 
       CAST(DATEADD(dd, 8-(DATEPART(dw, GETDATE())), GETDATE()) AS DATE) [WeekEnd]
  /*-- Week End
  --7->Saturday --8-> Sunday...*/

Running this today will produce this result:

WeekStart  WeekEnd
---------- ----------
2018-02-26 2018-03-04

if you have dates in your table, you can use them instead of the GETDATE()

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