|
在SQL Server在过去的五天里,我试图计算自2018年8月6日以来第一次观察到与今天相同天气的天数。每个城镇。
( s3 F- W2 q) {+ j2 q. ]数据如下:
# }1 D$ M ]6 I2 G1 T( v/ z( J --------- --------- -------- -------- -------- | Date | Toronto | Cairo | Zagreb | Ankara | --------- --------- -------- -------- -------- | 1.08.18 | Rain | Sun | Clouds | Sun || 2.08.18 | Sun | Sun | Clouds | Sun || 3.08.18 | Rain | Sun | Clouds | Rain || 4.08.18 | Clouds | Sun | Clouds | Clouds || 5.08.18 | Rain | Clouds | Rain | Rain || 6.08.18 | Rain | Sun | Sun | Sun | --------- --------- -------- -------- -------- 这需要很好地实施,但到目前为止,我只想单独查询每个城镇(将有几十个城镇,而不仅仅是四个城镇)。这是有用的,但不会扩展。
# z& |# u$ G$ p0 B' C这是多伦多的那个…
# s9 A3 w' O# U+ ?$ T& d8 dSELECT DATEDIFF(DAY,MIN([Date]),GETDATE() 1 FROM (SELECT TOP 5 * FROM Weather WHERE [Date] …正确返回4,因为今天下雨,过去5天第一次下雨是8月3日。
4 ]3 S( K& ?2 m) ?% b# c但我想回到的是这样一个表:
- d2 K& j( @5 G& H( N9 E6 ^: g --------- ------- -------- -------- | Toronto | Cairo | Zagreb | Ankara | --------- ------- -------- -------- | 4 | 5 | 1 | 5 | --------- ------- -------- -------- 此代码由@Used_By_Already稍微修改一下接受的答案:& G- U9 J" V$ [# D* n
CREATE TABLE mytable( Date date NOT NULL ,Toronto VARCHAR(9) NOT NULL ,Cairo VARCHAR(9) NOT NULL ,Zagreb VARCHAR(9) NOT NULL ,Ankara VARCHAR(9) NOT NULL);INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES Rain','Sun','Clouds','Sun');INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES Sun','Sun','Clouds','Sun');INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES ('20180803','Rain','Sun','Clouds','Rain');INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES Clouds','Sun','Clouds','Clouds');INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES Rain','Clouds','Rain','Rain');INSERT INTO mytable(Date,Toronto,Cairo,Zagreb,Ankara) VALUES Rain','Sun','Sun','Sun');with cte as ( select date,city,weather FROM ( SELECT * from mytable AS cp UNPIVOT ( Weather FOR City IN (Toronto,Cairo,Zagreb,Ankara) AS up )select date,city,weather,datediff(day,ca.prior,cte.date) 1 as daysPresentfrom ctecross apply select min(prev.date) as prior from cte as prev where prev.city = cte.city and prev.date between dateadd(day,-4,cte.date) and dateadd(day,0,cte.date) and prev.weather = cte.weather ) caorder by city,date但是,我现在要尝试的是,即使在过去五天有问题之后,我也应该继续计算. k0 A9 f, ^( r0 P" _
daysPresent。这意味着输出样本中最后标记的行应显示为6。逻辑是,如果它们之间的间隔小于5天,它们之间的天数将增加前一个数字。如果过去五天没有相同的天气,请返回1。
; h X/ Y8 G& G7 N6 ~" a; m我尝试了LEAD和LAG,但它不能正常工作。它是正确地添加了另一层,还是查询需要看起来完全不同?
! U) a- u- E8 n) _( j; Q我很困惑。2 `/ a) R5 h; O# C1 Q4 q$ [* ~
1 P4 ~6 u3 k3 \ j y8 @
解决方案: |
|