私はフィルターで連続した日付を結合するのに苦労しています。連続した日付を組み合わせる
例:
私のデータセット:私は必要
結果:(ちょうどpaid = 3
用)
スクリプトスキーマとデータの
CREATE TABLE [dbo].[NRFC](
[work_status] [int] NOT NULL,
[paid] [varchar](2) NOT NULL,
[from_date] [date] NOT NULL,
[to_date] [date] NOT NULL)
INSERT INTO [dbo].[NRFC]([work_status], [paid], [from_date], [to_date])
SELECT 101, N'3', '20100101 00:00:00.000', '20100116 00:00:00.000' UNION ALL
SELECT 101, N'3', '20100116 00:00:00.000', '20150128 00:00:00.000' UNION ALL
SELECT 101, N'5', '20150129 00:00:00.000', '20150331 00:00:00.000' UNION ALL
SELECT 101, N'4', '20150401 00:00:00.000', '20150512 00:00:00.000' UNION ALL
SELECT 101, N'3', '20160101 00:00:00.000', '20170315 00:00:00.000' UNION ALL
SELECT 101, N'4', '20170316 00:00:00.000', '20170317 00:00:00.000' UNION ALL
SELECT 101, N'3', '20090101 00:00:00.000', '20090110 00:00:00.000' UNION ALL
SELECT 101, N'3', '20090111 00:00:00.000', '20090115 00:00:00.000' UNION ALL
SELECT 101, N'3', '20090115 00:00:00.000', '20090331 00:00:00.000' UNION ALL
SELECT 101, N'3', '20090401 00:00:00.000', '20091212 00:00:00.000'
そして、これまでのところ、私のコード:
;WITH Grouped (
from_date
,to_date
,paid
,first
)
AS (
SELECT from_date
,to_date
,paid
,isnull((
SELECT CASE
WHEN paid <> w.paid
THEN 1
ELSE 0
END
FROM NRFC
WHERE from_date = (
SELECT max(from_date)
FROM NRFC
WHERE from_date < w.from_date
)
), 1) AS first
FROM NRFC w
WHERE paid = 3
)
SELECT min(from_date) AS from_date
,max(to_date) AS to_date
,paid
FROM (
SELECT from_date
,to_date
,paid
,isnull((
SELECT sum(first)
FROM grouped
WHERE from_date > g.from_date
), 0) AS part
FROM grouped g
) p
GROUP BY p.part
,p.paid
ORDER BY from_date
「SELECT *、DATEDIFF(DAY、TODATE)、OVER(ORDER BY TO_DATE))> = 1 THEN 0 ELSE 1 END newRow FROM @ NRFC'これにより、新しい行 – SQLMason
ありがとうSQLMason、SQL 2008にあります – Sreedhar
私はそれに気付かなかったことを申し訳ありません。 – SQLMason