我想做点什么来填补两个时间戳之间的日期。例如,有人在1月份被录取并在3月出院,我想知道他们按月分开,例如,
我的原始数据看起来像,
然后我想得到的是,
我知道"循环"应该能够在SQL Oracle中做到这一点,但不知道如何。与此类似的人可以提供一些提示和帮助。提前谢谢!
答案 0 :(得分:1)
/*
WITH tab AS (
SELECT 1 ID, to_date('20140105', 'YYYYMMDD') admission, to_date('20140331', 'YYYYMMDD') discharge FROM dual
UNION ALL SELECT 2, to_date('20140207', 'YYYYMMDD') admission, to_date('20140212', 'YYYYMMDD') discharge FROM dual
)
*/
SELECT ID, admission, discharge,
CASE WHEN trunc(add_months(admission, lvl), 'MM') = trunc(admission, 'MM')
THEN admission
ELSE trunc(add_months(admission, lvl), 'MM') END,
CASE WHEN trunc(add_months(admission, lvl+1), 'MM') <= trunc(discharge, 'MM')
THEN trunc(add_months(admission, lvl+1), 'MM') - 1
ELSE discharge END
FROM (SELECT lvl FROM (SELECT LEVEL - 1 lvl FROM dual
CONNECT BY LEVEL <=
(SELECT ceil(months_between(MAX(discharge), MIN(admission)))+1 FROM tab))
) JOIN tab ON trunc(add_months(admission, lvl), 'MM') <= discharge
ORDER BY ID, lvl;
1)使用CONNECT BY等级&lt; = N生成一个数字从0到N-1的表格(月份之间的最大差异)
2)将此表与您的tab
一起生成结果。