我表格中的数据如下所示
PAY_END_DT Sal
10/27/2013 0
11/10/2013 0
11/24/2013 2473.14
12/08/2013 0
01/19/2014 0
02/02/2014 0
02/16/2014 0
我想要的结果应如下所示
10/27/2013 11/10/2013
12/08/2013 02/16/2014
我需要一个SQL来生成这个结果集..请帮助
答案 0 :(得分:0)
SELECT
employee_id,
MIN(pay_end_dt) AS island_min_pay_end_dt,
MAX(pay_end_dt) AS island_max_pay_end_dt
FROM
(
SELECT
pay_end_dt,
ROW_NUMBER() OVER (PARTITION BY employee_id,
ORDER BY pay_end_dt ) AS full_set_ordinal,
ROW_NUMBER() OVER (PARTITION BY employee_id, sal
ORDER BY pay_end_dt ) AS zero_set_ordinal
FROM
yourTable
)
AS sorted_set
WHERE
sal = 0
GROUP BY
employee_id,
full_set_ordinal - zero_set_ordinal
;
以您的数据为例:
PAY_END_DT Sal FULL_SET_ORIDINAL ZERO_SET_ORDINAL "FULL - ZERO"
10/27/2013 0 1 1 0
11/10/2013 0 2 2 0
11/24/2013 2473.14 3 1 2
12/08/2013 0 4 3 1
01/19/2014 0 5 4 1
02/02/2014 0 6 5 1
02/16/2014 0 7 6 1
然后,我们只允许包含行WHERE sal = 0
然后GROUP BY "FULL - ZERO"
来获取我们的两个集合,然后最后应用MIN()
和MAX()
函数。
正如评论中所述,这被称为" Gaps and Islands"。
1 1 1 1
0 0 0 0 0
1 2 3 4 5 6 7 8 9 - ordinal from the whole set
1 2 3 4 - ordinal from just the "islands"
1 2 3 4 5 - ordinal from just the "gaps"
2 2 2 3 - ordinal of the "islands" (whole_set_id - islands_id)
0 0 3 4 4 - ordinal of the "gaps" (whole_set_id - gaps_id)
答案 1 :(得分:-2)
;)
SELECT "10/27/2013 11/10/2013"
UNION
SELECT "12/08/2013 02/16/2014"