我有一个如下表格,我希望复制记录,而最小日期小于或等于最大日期
686151209 E13232677 1333439 2017-10-23
686151209 E13232677 1333439 2017-10-26
我希望得到如下结果集
686151209 E13232677 1333439 2017-10-23
686151209 E13232677 1333439 2017-10-24
686151209 E13232677 1333439 2017-10-25
86151209 E13232677 1333439 2017-10-26
答案 0 :(得分:1)
您并使用spt_values获取连续数字:
;WITH testdata(col1,col2,col3,col4)AS(
SELECT '686151209','E13232677','1333439','2017-10-23' UNION all
SELECT '686151209','E13232677','1333439','2017-10-26'
)
SELECT col1,col2,col3,DATEADD(d,sv.number-1,a.mindate) AS col4,sv.number FROM (
SELECT col1,col2,col3,CONVERT(DATE,MIN(col4)) AS mindate,CONVERT(DATE,MAX(col4)) AS maxdate
FROM testdata AS t
group by col1,col2,col3
) AS a
INNER JOIN master.dbo.spt_values AS sv ON sv.type='P' AND sv.number BETWEEN 1 AND DATEDIFF(d,mindate,maxdate)+1
+-----------+-----------+---------+------------+--------+ | col1 | col2 | col3 | col4 | number | +-----------+-----------+---------+------------+--------+ | 686151209 | E13232677 | 1333439 | 2017-10-23 | 1 | | 686151209 | E13232677 | 1333439 | 2017-10-24 | 2 | | 686151209 | E13232677 | 1333439 | 2017-10-25 | 3 | | 686151209 | E13232677 | 1333439 | 2017-10-26 | 4 | +-----------+-----------+---------+------------+--------+
答案 1 :(得分:0)
一种方法是数字表。如果你没有太多行,我也喜欢递归CTE:
with cte as (
select col1, col2, col3, mind, maxd
from (select col1, col2, min(dte) as mind, max(dte) as maxd
from t
group by col1, col2, col3
) t
union all
select col1, col2, col3, dateadd(day, 1, mind), maxd
from cte
where dateadd(day, 1, mind) < maxd
)
select col1, col2, col3, mind
from cte;
除非您设置了最大递归选项,否则每个col1
/ col2
组合限制为100行。
答案 2 :(得分:0)
或者像这样:
CREATE TABLE temp
(
ID BIGINT,
CODE VARCHAR(50),
ID2 BIGINT,
DATE DATE
);
INSERT INTO temp VALUES (686151209, 'E13232677', 1333439, '2017-10-23'),
(686151209, 'E13232677', 1333439, '2017-10-26');
SELECT generate_series(T.D1::timestamp, T.D2::timestamp, interval '1 day')::date
FROM
(
SELECT A.id, A.code, A.id2, A.dates AS D1, B.dates AS D2
FROM temp A
LEFT JOIN temp b ON (A.id = B.id AND
A.code=B.code AND
A.id2 = B.id2 AND
B.dates > A.dates)
WHERE B.id IS NOT NULL
) T;