有人可以通过WITH()子句发现错误吗?

时间:2018-10-24 16:40:41

标签: sql oracle common-table-expression

SQL无法识别我在主SELECT语句中调用的变量。我正在调用的变量是execs.block_order_quantity。我在查询开始的WITH语句中将此变量命名。代码在下面,错误附加为图片。我已经运行了没有WITH execs as(的select语句,它的运行正常。

WITH execs as(SELECT th.exec_id, SUM(eha.tck_ord_qty) as "BLOCK_ORDER_QUANTITY"  
FROM t1 eha
join t2 th
on eha.exec_id = th.exec_id
where th.trdng_desk_sname IN ('NAME')
and th.trd_dt between to_date('201840101', 'YYYYMMDD')
and to_date ('20140301', 'YYYYMMDD')
and exists
    (SELECT 1
     FROM t2t eth
     WHERE eth.TRD_ID = eha.TRD_ID
     AND eth.trd_stat_cd = 'EX')
group by th.exec_id)
SELECT DISTINCT
th.trd_dt as "TRADE_DATE",
eah.ord_cap_qty as "CAP_AMOUNT",
execs.block_order_quantity as "BLOCK_ORDER_QUANTITY", 
eah.alloc_ovrrd_rsn_cd as "ALLOC_OVRRD_RSN_CD",
  CASE   --create allocation case id 
        WHEN(eh.manl_alloc_ind = 'Y'
            OR NVL (eah.trdr_drct_qty, 0) > 0
            OR NVL (eah.trdr_drct_wgt_ratio, 0) > 0)
        THEN
            'Y'
        ELSE
            'N'
      END 
        AS "ALLOCATION_OVRRD_IND",
      CASE
        WHEN (eh.manl_alloc_ind = 'Y'
             OR NVL (eah.trdr_drct_qty, 0) > 0
             OR NVL (eah.trdr_drct_wgt_ratio, 0) > 0)
        THEN
          TH.EXEC_TMSTMP
        ELSE
          NULL
       END
         AS "ALLOCATION_OVRRD_TIMESTAMP",
eah.alloc_adj_assets_rt_curr_amt as "FUND_ADJ_NET_ASSETS",
eah.as_alloc_exec_hld_qty as "FUND_HOLDINGS_QUANTITY",
th.as_trd_iv_lname as "SECURITY_NAME",
th.as_trd_fmr_ticker_symb_cd as "TICKER",
   CASE  
      WHEN NVL(th.limit_prc_amt, 0) > 0 THEN 'LIMIT' ELSE NULL END
          AS "FUND_ORDER_TYPE"
from t1 eah
join t3 eh
on eah.exec_id = eah.exec_id
join t2 th
on th.trd_id = eah.trd_id
join t4 tk
on tk.tck_id = eah.tck_id
join t5 pm
on eah.pm_person_id_src = pm.person_id_src
where th.trdng_desk_sname IN('NAME')
and th.trd_dt between to_date('20140101', 'YYYYMMDD')
and to_date ('20140301', 'YYYYMMDD')
and rownum < 15

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要在主查询中加入execs公用表表达式(CTE)名称,例如:

...
from t1 eah
join t3 eh
on eah.exec_id = eah.exec_id
join t2 th
on th.trd_id = eah.trd_id
join execs
on execs.exec_id = eh.exec_id
join t4 tk
...

我不确定您是否确实要在此处进行CTE,看起来您可以在引用相同表时在主查询中进行汇总;但是可能有些我想念的东西,例如后来的联接引入的重复项。

偶然地,那里的第一个on子句看起来是错误的,因为双方都引用了同一张表中的同一列;所以应该是:

...
from t1 eah
join t3 eh
on eh.exec_id = eah.exec_id
join t2 th

有时distinct表示存在不正确的联接,并且您想抑制某些重复项,而这些重复项本来就不应该存在,因此一旦确定了联接条件,就可能不需要它。如果以前给出了错误的结果,那么这可能也允许简单的聚合工作。 (或者可能还有其他不适当的原因。)

此外,where rownum < 15将给出不确定的行集,因为在应用该过滤器之前您不对结果集进行排序。