我卡在查询中,表是
TP_DEALNUM DEALDATE MATURITYDATE TP_DEALTYPE TP_NETVALUE
500 20180521 20180524 NBORR 209221500
501 20180525 20180527 NBORR 249221500
502 20180527 20180527 NBORR 747664500
601 20180530 20180531 CBORR 1000000000
602 20180530 20180531 CBORR 500000000
我的查询是 如果Dealdate和MATURITYDATE之间的日期差为= 2,那么我需要
DEALDATE TP_NETVALUE
20180525 249221500
20180526 249221500
并且如果dealdate和MATURITYDATE之间的日期差为= 3,那么我需要
DEALDATE TP_NETVALUE
20180521 209221500
20180522 209221500
20180523 209221500
日期差将增加到14点
我在下面的查询中尝试过,但是没有得到输出
WITH cte AS (
SELECT tp_dealnum,dealdate, maturitydate,TP_DEALTYPE,TP_NETVALUE,
(maturitydate -dealdate) AS DateDiff
FROM tablename)
SELECT case WHEN datediff=2 THEN dealdate+1
WHEN datediff=3 THEN dealdate+1 END AS dealdate_1,
tp_netvalue FROM cte
WHERE DateDiff >= 2
答案 0 :(得分:0)
我建议在这里使用日历表方法。保留所有交易日期的记录,这些记录将填补当前表中的空白,然后加入该记录:
WITH dates AS (
SELECT date '2018-05-01' AS DEALDATE FROM dual UNION ALL
SELECT date '2018-05-02' FROM dual UNION ALL
SELECT date '2018-05-02' FROM dual UNION ALL
....
SELECT date '2018-05-30' FROM dual UNION ALL
SELECT date '2018-05-31' FROM dual
)
SELECT
d.DEALDATE,
t.TP_NETVALUE
FROM dates d
INNER JOIN tablename t
ON d.DEALDATE BETWEEN t.DEALDATE AND t.MATURITYDATE - 1
WHERE
t.MATURITYDATE - t.DEALDATE BETWEEN 2 AND 3;
请注意,这只会生成丢失的数据。如果要将其合并到其他查询/逻辑中,则必须做其他工作。
答案 1 :(得分:0)
关键是生成另一个具有这样的间歇日期的CTE-
WITH deal AS
(SELECT 500 TP_DEALNUM,
20180521 DEALDATE,
20180524 MATURITYDATE,
'NBORR' TP_DEALTYPE,
209221500 TP_NETVALUE
FROM dual
UNION ALL
SELECT 501, 20180525, 20180527, 'NBORR', 249221500 FROM dual
UNION ALL
SELECT 502, 20180527, 20180527, 'NBORR', 747664500 FROM dual
UNION ALL
SELECT 601, 20180530, 20180531, 'CBORR', 1000000000 FROM dual
UNION ALL
SELECT 602, 20180530, 20180531, 'CBORR', 500000000 FROM dual),
daterange AS
(SELECT min (dealdate) start_date, max (maturitydate) end_date
FROM deal),
intermittent_date AS
( SELECT start_date + level - 1 AS int_date
FROM daterange
CONNECT BY start_date + level - 1 <= end_date)
SELECT id.int_date dealdate, dl.tp_netvalue
FROM deal dl
INNER JOIN intermittent_date id
ON id.int_date BETWEEN dl.dealdate AND dl.maturitydate - 1
WHERE dl.maturitydate - dl.dealdate = 2;
输出:
DEALDATE TP_NETVALUE
---------- -----------
20180525 249221500
20180526 249221500