1
我必須爲Microsoft SQL Server中一年中兩個代碼之間交替的一個特定房間分配顏色代碼。唯一字段是日曆的每個單獨日期。在SQL Server 2012中使用CTE獲取連續日期
因此示例行將如下所示。
weekDay colorName RoomNum
2017-01-01 Blue 100
2017-01-02 Red 100
顏色代碼需要分配給2種顏色之間的每個周交替從星期一(即在一週的開始)至週日算作周的端部。因此,2017年起週一1月2日,我需要下面的模式,通過下一日曆年如此繼續的2018年
2017-01-02 Red 100
2017-01-03 Red 100
2017-01-04 Red 100
2017-01-05 Red 100
2017-01-06 Red 100
2017-01-07 Red 100
2017-01-08 Red 100
2017-01-09 Blue 100
2017-01-10 Blue 100
2017-01-11 Blue 100
2017-01-12 Blue 100
2017-01-13 Blue 100
2017-01-14 Blue 100
2017-01-15 Blue 100
2017-01-16 Red 100
.
.
.
我有以下CTE結束,但它的第一個每週6天分配,然後分配14從每個星期一到星期天開始,每隔7天開始一週。我究竟做錯了什麼?謝謝!
DECLARE @tableTest TABLE (weekDay datetime, colorName varchar(50), roomNum int);
DEClARE @begindate datetime = '01/02/17';
declare @enddate datetime = '12/31/18';
;with
N0 as (SELECT 1 as n UNION ALL SELECT 1)
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2)
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2)
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2)
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2)
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2)
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2)
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6)
INSERT @tableTest (weekDay, roomNum)
SELECT DATEADD(day,num-1,@begindate) as thedate, 100
FROM nums
WHERE num <= DATEDIFF(day,@begindate,@enddate) + 1
;with weekNumber as (
SELECT weekDay, colorName, roomNum, (DATEPART(ww, weekDay)/2) % 2 as schedule FROM @tableTest
)
UPDATE weekNumber
SET colorName = CASE WHEN weekNumber.schedule = 0 THEN 'Red' ELSE 'Blue' END
SELECT * FROM @tableTest