需要在null处重复上一次交易

时间:2018-09-20 04:11:09

标签: sql oracle

我的存储过程:

SELECT B.ETADATE,
  a.NAME,
  a.CATEGORY ,
  a.TYPE,
  a.STOCK
FROM
  (SELECT TO_CHAR(TO_DATE(FROM_DATE,'DD-MM-YYYY HH24:MI:SS')) AS "FROM_DATE",
    NAME                                                      AS "NAME",
    CATEGORY                                                  AS "CATEGORY",
    TYPE                                                      AS "TYPE",
    BALANCE                                                   AS "BALANCE"
  FROM VW_NET_STOCK_POSITION
  ) a,
  (SELECT dt + LEVEL AS ETADate
  FROM
    (SELECT TRUNC (TO_DATE ('01-09-2018 00:00:00', 'DD-MM-YYYY HH24:MI:SS'), 'MM') - 1 AS dt
    FROM DUAL
    ) D
    CONNECT BY LEVEL <= sysdate - dt
  ) B
WHERE a.FROM_DATE(+) = B.ETADATE
ORDER BY ETADate;

,我的输出是:

enter image description here

但是我希望在'null'处将其替换为之前的交易。

喜欢这个

想要这样的输出

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用带有LAST_VALUE选项的IGNORE NULLS分析函数来制作 SQL ,如下所示:

SELECT ETADATE,
       LAST_VALUE(NAME)  IGNORE NULLS OVER (ORDER BY etadate) as NAME, 
       LAST_VALUE(CATEGORY) IGNORE NULLS OVER (ORDER BY etadate) as CATEGORY,
       LAST_VALUE(TYPE) IGNORE NULLS OVER (ORDER BY etadate ) as TYPE,
       LAST_VALUE(BALANCE) IGNORE NULLS OVER (ORDER BY etadate ) as STOCK
  FROM 
    (SELECT TO_CHAR(TO_DATE(FROM_DATE,'DD-MM-YYYY HH24:MI:SS')) AS "FROM_DATE",
      NAME                                                      AS "NAME",
      CATEGORY                                                  AS "CATEGORY",
      TYPE                                                      AS "TYPE",
      BALANCE                                                   AS "BALANCE"
    FROM VW_NET_STOCK_POSITION
    ) a LEFT OUTER JOIN
    (SELECT dt + LEVEL AS ETADate
       FROM
      (SELECT TRUNC (TO_DATE ('01-09-2018 00:00:00', 'DD-MM-YYYY HH24:MI:SS'), 'MM') - 2 
           AS dt
      FROM DUAL
      ) D
      CONNECT BY LEVEL <= trunc(sysdate) - dt
    ) B
   ON ( a.FROM_DATE = B.ETADATE )
ORDER BY ETADate;

,并且更喜欢使用ANSI JOIN标准。

SQL Fiddle Demo

答案 1 :(得分:0)

请勿将+用于外部联接!您的问题的解决方案是LAG(. . . IGNORE NULLS)。但是查询可以清除。

我建议这样写:

WITH dates as (
      SELECT (dt + level - 1) as etadate
      FROM (SELECT TRUNC(DATE '2018-09-01', 'MM') - 1 AS dt
            FROM DUAL
           ) d
      CONNECT BY LEVEL <= sysdate - dt + 1  -- to get today's date
  ) 
SELECT d.etadate,
       COALESCE(nsp.name, LAG(nsp.name IGNORE NULLS) OVER (ORDER BY d.etadate)) as name,
       COALESCE(nsp.category, LAG(nsp.category IGNORE NULLS) OVER (ORDER BY d.etadate)) as category,
       COALESCE(LAG(nsp.type IGNORE NULLS) OVER (ORDER BY d.etadate), type) as type,
       COALESCE(LAG(nsp.stock IGNORE NULLS) OVER (ORDER BY d.etadate), stock) as stock
FROM dates d LEFT JOIN
     VW_NET_STOCK_POSITION nsp
     ON d.etadate = TRUNC(nsp.from_date)
ORDER BY d.ETADate;