我真的很想清理此sql代码,但不太确定最佳方法。任何建议,将不胜感激(它会持续多达20次。)
我曾想过可能是一个循环,但不太确定如何在sql中执行此操作,也许我需要为此设置一个外部函数?任何建议将不胜感激。
WHEN Date BETWEEN Sea.StartDate+(27*1) AND Sea.StartDate+(27*2) THEN 2
WHEN Date BETWEEN Sea.StartDate+(27*2) AND Sea.StartDate+(27*3) THEN 3
WHEN Date BETWEEN Sea.StartDate+(27*3) AND Sea.StartDate+(27*4) THEN 4
WHEN Date BETWEEN Sea.StartDate+(27*4) AND Sea.StartDate+(27*5) THEN 5
WHEN Date BETWEEN Sea.StartDate+(27*5) AND Sea.StartDate+(27*6) THEN 6
WHEN Date BETWEEN Sea.StartDate+(27*6) AND Sea.StartDate+(27*7) THEN 7
WHEN Date BETWEEN Sea.StartDate+(27*7) AND Sea.StartDate+(27*8) THEN 8
WHEN Date BETWEEN Sea.StartDate+(27*8) AND Sea.StartDate+(27*9) THEN 9
WHEN Date BETWEEN Sea.StartDate+(27*9) AND Sea.StartDate+(27*10) THEN 10
END) AS Cycle,
Convert(BIT, CASE
WHEN Date = Sea.StartDate OR
Date = Sea.StartDate+(28*1) OR
Date = Sea.StartDate+(28*2) OR
Date = Sea.StartDate+(28*3) OR
Date = Sea.StartDate+(28*4) OR
Date = Sea.StartDate+(28*5)
THEN 1
ELSE 0
END) AS CStart
答案 0 :(得分:1)
正如@Bart Hofland所说,具体情况因数据库而异。
本着“教人钓鱼...”的精神,对于SQL Server,第一部分将是这样的:
select datediff(d, startDate, date)/27
这应该有助于您的周期。您可以+/-向上或向下,但是我确定要点。
第二个计算CStart的条件只是一个小问题。有多种实现方法,但是我看不出有更好的选择。