[英]SQL Group By Day Range
我有一個表OutletVisit
,它有一個DTOEntry
列,它是DateTime格式。
表結構
DTOEntry | OutletID
18-01-2016| 1
18-01-2016| 2
18-01-2016| 3
18-01-2016| 4
27-01-2016| 1
27-01-2016| 2
27-01-2016| 3
29-01-2016| 4
現在我想要的輸出基本上group by
從Thursday
[包含]到Wednesday
From | To | OutletID | ActualDate
14-01-2016| 20-01-2016 | 1 | 18-01-2016
14-01-2016| 20-01-2016 | 2 | 18-01-2016
14-01-2016| 20-01-2016 | 3 | 18-01-2016
14-01-2016| 20-01-2016 | 4 | 18-01-2016
21-01-2016| 27-01-2016 | 1 | 27-01-2016
21-01-2016| 27-01-2016 | 2 | 27-01-2016
21-01-2016| 27-01-2016 | 3 | 27-01-2016
28-01-2016| 03-02-2016 | 4 | 29-01-2016
如何為此編寫動態SQL
。
提前致謝
目前尚不清楚為什么你想要“動態sql”,但你可以使用日期函數計算每周四開始的一周。
MS SQL Server 2014架構設置 :
CREATE TABLE OutletVisit
([DTOEntry] datetime, [OutletID] int)
;
INSERT INTO OutletVisit
([DTOEntry], [OutletID])
VALUES
('2016-01-18 00:00:00', 1),
('2016-01-18 00:00:00', 2),
('2016-01-18 00:00:00', 3),
('2016-01-18 00:00:00', 4),
('2016-01-27 00:00:00', 1),
('2016-01-27 00:00:00', 2),
('2016-01-27 00:00:00', 3),
('2016-01-29 00:00:00', 4)
;
查詢1 :
SELECT
ca.weekstart
, DATEADD(DAY, 6, ca.weekstart) AS weekfinish
, ov.*
FROM OutletVisit ov
CROSS APPLY (
SELECT
DATEADD(DAY, (DATEDIFF(DAY, -4, DTOEntry) / 7) * 7, -4) AS weekstart
) AS ca
可以使用的替代方法,使用“派生表”(或“子查詢”):
SELECT
weekstart
, DATEADD(DAY, 6, weekstart) AS weekfinish
, DTOEntry
, OutletID
FROM (
SELECT
DATEADD(DAY, (DATEDIFF(DAY, -4, DTOEntry) / 7) * 7, -4) AS weekstart
, ov.DTOEntry
, ov.OutletID
FROM OutletVisit ov
) AS derived
;
結果 :
| weekstart | weekfinish | DTOEntry | OutletID |
|---------------------------|----------------------------|---------------------------|----------|
| January, 14 2016 00:00:00 | January, 20 2016 00:00:00 | January, 18 2016 00:00:00 | 1 |
| January, 14 2016 00:00:00 | January, 20 2016 00:00:00 | January, 18 2016 00:00:00 | 2 |
| January, 14 2016 00:00:00 | January, 20 2016 00:00:00 | January, 18 2016 00:00:00 | 3 |
| January, 14 2016 00:00:00 | January, 20 2016 00:00:00 | January, 18 2016 00:00:00 | 4 |
| January, 21 2016 00:00:00 | January, 27 2016 00:00:00 | January, 27 2016 00:00:00 | 1 |
| January, 21 2016 00:00:00 | January, 27 2016 00:00:00 | January, 27 2016 00:00:00 | 2 |
| January, 21 2016 00:00:00 | January, 27 2016 00:00:00 | January, 27 2016 00:00:00 | 3 |
| January, 28 2016 00:00:00 | February, 03 2016 00:00:00 | January, 29 2016 00:00:00 | 4 |
注意在輸出時控制日期時間值的顯示使用FORMAT()或CONVERT()。 Sqlfiddle的顯示默認值已在上面的結果中使用。
另請注意,實際上一周開始於(比如)2016年1月14日00:00:00,並於2016年1月21日00:00:00結束,持續7天。 “weekfinishes”列使用6天的持續時間來匹配您的預期結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.