我必须在Microsoft SQL Server中为一年中的两个代码之间交替分配一个特定房间的颜色代码。唯一字段是日历的每个日期。
因此示例行如下所示。
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天,而不是每周一至周日开始七天。我究竟做错了什么?谢谢!
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
答案 0 :(得分:0)
你正在进行分割和模数运算,这会导致你加宽&#34;宽度&#34;模数,如果这个术语对你有意义。 :)
换句话说,而不是对1,2,3,4等模数进行模数。
你对1,1.5,2,2.5,3等做模数。得到它吗?
无论如何,解决方案是将最终更新更改为:
;with weekNumber as (
SELECT weekDay, colorName, roomNum, (DATEPART(ww, weekDay)) % 2 as schedule FROM @tableTest
)
UPDATE weekNumber
SET colorName = CASE WHEN weekNumber.schedule = 0 THEN 'Red' ELSE 'Blue' END