Grouping by the Week by using datepart function : DATEPART « Date Functions « SQL Server / T-SQL Tutorial






4>
5>
6> CREATE TABLE Orders (
7>      OrderID int IDENTITY (1, 1) NOT NULL ,
8>      CustomerID nchar (5) NULL ,
9>      EmployeeID int NULL ,
10>     OrderDate datetime NULL ,
11>     RequiredDate datetime NULL ,
12>     ShippedDate datetime NULL ,
13>     ShipVia int NULL ,
14>     Freight money NULL DEFAULT (0),
15>     ShipName nvarchar (40) NULL ,
16>     ShipAddress nvarchar (60) NULL ,
17>     ShipCity nvarchar (15) NULL ,
18>     ShipRegion nvarchar (15) NULL ,
19>     ShipPostalCode nvarchar (10) NULL ,
20>     ShipCountry nvarchar (15) NULL
21> )
22> GO
1>
2>
3> SELECT od - wd + 1 AS week_start, od + 7 - wd AS week_end,
4>   COUNT(*) AS numorders
5> FROM (SELECT OrderID AS oid, OrderDate AS od,
6>         DATEPART(weekday, OrderDate + @@DATEFIRST - 1) AS wd
7>       FROM dbo.Orders) AS D
8> GROUP BY od - wd + 1, od + 7 - wd;
9> GO
week_start              week_end                numorders
----------------------- ----------------------- -----------

(0 rows affected)
1>
2> drop table Orders;
3> GO
1>
2>








10.8.DATEPART
10.8.1.DATEPART returns part of a date as an integer value.
10.8.2.Values for the datepart parameter.
10.8.3.WHERE DATEPART(WEEKDAY, pubdate) = 3
10.8.4.where DATEPART(DAY, pubdate) BETWEEN 8 AND 14
10.8.5.where DATEDIFF(WEEK, pubdate, GETDATE()) <= 48
10.8.6.DATEPART Function returns the integer value of the datepart specified: DATEPART(datepart,date)
10.8.7.select DATEPART(day, '2002-09-30 11:35:00')
10.8.8.select DATEPART(month, '2002-09-30 11:35:00')
10.8.9.select DATEPART(year, '2002-09-30 11:35:00')
10.8.10.select DATEPART(hour, '2002-09-30 11:35:00')
10.8.11.select DATEPART(minute, '2002-09-30 11:35:00')
10.8.12.select DATEPART(second, '2002-09-30 11:35:00')
10.8.13.select DATEPART(quarter, '2002-09-30 11:35:00')
10.8.14.select DATEPART(dayofyear, '2002-09-30 11:35:00')
10.8.15.select DATEPART(week, '2002-09-30 11:35:00')
10.8.16.select DATEPART(weekday, '2002-09-30 11:35:00')
10.8.17.select DATEPART(m,'2002-09-30')
10.8.18.SELECT DATEPART(dd, '7/5/99')
10.8.19.SELECT DATEPART(dd, '7/5/00')
10.8.20.IF DATEDIFF(dd, '7/5/99','7/5/00') = 0
10.8.21.(DATEPART(mm, @date1) = DATEPART(mm, @date2))
10.8.22.(DATEPART(dd, @date1) = DATEPART(dd, @date2))
10.8.23.(DATEPART(yy, @date1) = DATEPART(yy, @date2)
10.8.24.Identifying Weekday
10.8.25.Grouping by the Week by using datepart function