在按值分组的列中查询连续月份的结果

时间:2015-03-16 23:18:14

标签: sql sql-server group-by

以下是样本数据:

Name | Hours | RDate       | Company |
------------------------------------
A    |0      |2014-08-01   |W
A    |0      |2014-07-01   |W
A    |0      |2014-06-01   |W
A    |0      |2014-05-01   |W
B    |0      |2014-08-01   |X
C    |0      |2014-07-01   |Y
C    |0      |2014-06-01   |Y
D    |0      |2014-08-01   |V     
D    |0      |2014-07-01   |Z

以下是我想要的结果:

Name | Hours | RDate       | Company |
------------------------------------
A    |0      |2014-08-01   |W
A    |0      |2014-07-01   |W
A    |0      |2014-06-01   |W
A    |0      |2014-05-01   |W
C    |0      |2014-07-01   |Y
C    |0      |2014-06-01   |Y

所以问题是:

如何仅针对同一RDate及相同的2014-08-01, 2014-07-01列{I} 2014-08-01, 2014-06-01name不满足)中的company连续月份的结果{{1}}

2 个答案:

答案 0 :(得分:2)

我认为这有点是Grouping Islands of Contiguous Dates问题的变体。

;WITH Cte AS(
    SELECT *,
        RN = DATEADD(MONTH, - ROW_NUMBER() OVER (PARTITION BY Name, Company ORDER BY RDate), RDate)
    FROM Test
)
,CteCount AS(
    SELECT *,
        CC = COUNT(*) OVER(PARTITION BY Name, Company, RN)
    FROM Cte
)
SELECT
    Name, Hours, RDate, Company
FROM CteCount
WHERE CC > 1

SQL FIDDLE

答案 1 :(得分:1)

虽然@wewesthemenace的答案更有效率,但我试图找出自己正在研究的解决方案并且它有效;将之前标记的答案保持为标记,因为它更好。这实际上也有效:

SELECT 
    one.*
FROM 
    foo one 
INNER JOIN 
    foo two
ON 
    (one.Name = two.Name and one.Company = two.Company) 
WHERE
    CONVERT(int,FORMAT(two.Date, 'yyyyMM')) - CONVERT(int,FORMAT(one.ACSS_Date, 'yyyyMM')) = 1
ORDER BY
    one.Name
    ,one.Date DESC