没有循环记录集的SQL子查询

时间:2017-08-05 20:54:35

标签: sql loops subquery

这是一个简单的查询:

SELECT        fDATE, fRAIN
FROM            tRAIN
WHERE        (fRAIN >=5)

检索到的查询可能类似于:

Query Result

现在,我希望获得与较长雨季相对应的子集,在这种情况下,日期为10月9日至13日。 ¿有一种方法可以在没有循环记录集的情况下执行此操作吗?

感谢您的帮助。此致

1 个答案:

答案 0 :(得分:0)

我已根据How to get count of consecutive dates

发布的答案完成任务
WITH Q4 AS (
SELECT Q3.fDate, Q3.RW
FROM
(SELECT 
RW=ROW_NUMBER() OVER( PARTITION BY GRP  ORDER BY fDate) ,fDate
FROM
(
SELECT 
fDate, DATEDIFF(Day, '1900-01-01' , fDate)- ROW_NUMBER() OVER( ORDER BY 
fDate ) AS GRP
FROM (SELECT CONVERT(DATE,CONCAT(fYEAR , '/' , fMONTH , '/' ,fDAY),111) AS fDate, 
fRAIN 
FROM tRain
WHERE (fRain >= _value AND fStation = '_string' AND fYear = _value)
) Q1 
) Q2
) Q3
)
SELECT (DATEADD(DAY,-Q4.RW+1,Q4.fDate)) AS Start_Date, Q4.fDate AS 
Final_Date, Q4.RW as Season_Length
FROM Q4
WHERE Q4.RW= (SELECT TOP 1 MAX(Q4.RW) FROM Q4)

输出如下:

QUERY RESULT

此致