可以使用JOIN ON语法的内联视图?

时间:2018-02-12 15:17:41

标签: sql join view inline

我有两个内联视图,我可以通过经典的连接方法加入。结果如预期。

但是,尝试适应JOIN ON语法,我看不出如何。限制?需要吗?或者需要创建两个单独的视图然后应用 - 我认为会起作用。在这方面找不到任何东西。

视图如下,试图在买入和卖出之间找到匹配。

select BUY.*, SELL.* from (
select Z.*, 'LONG' from (
select X.commodity, X.market_place, X.max_qty, Y.maturity_dt, rank() over 
(partition by X.commodity, X.market_place order by y.maturity_dt ASC) as 
rank_val
  from
 (select commodity, market_place, max(qty) as max_qty
   from OPEN_POSITIONS
 where prod_type = 'future'
   and qty > 0
  group by commodity, market_place
 ) X,
  open_positions Y 
 where Y.qty = X.max_qty
   and Y.commodity = X.commodity
   and Y.prod_type = 'future'
   and Y.market_place = X.market_place ) Z
 where Z.rank_val = 1 ) BUY, 
  (
select Z.*, 'SHORT' from (
select X.commodity, X.market_place, X.min_qty, Y.maturity_dt, rank() over 
(partition by X.commodity, X.market_place order by y.maturity_dt ASC) as 
rank_val
  from
 (select commodity, market_place, min(qty) as min_qty
  from OPEN_POSITIONS
 where prod_type = 'future'
   and qty < 0
  group by commodity, market_place
 ) X,
  open_positions Y 
  where Y.qty = X.min_qty
   and Y.commodity = X.commodity
   and Y.prod_type = 'future'
   and Y.market_place = X.market_place ) Z
where Z.rank_val = 1) SELL
where BUY.commodity = SELL.commodity
  and BUY.market_place = SELL.market_place

2 个答案:

答案 0 :(得分:1)

您可以根据数据库尝试以下内容。

  ;With AllData AS 
  (
        select commodity, market_place, qty
            from OPEN_POSITIONS
        where prod_type = 'future'
  ),
  X AS 
  (
    SELECT
        commodity, market_place, max(qty) as max_qty
    FROM    AllData
    WHERE  qty > 0
    group by commodity, market_place
  ),
  Z AS
  (
    SELECT
        X.commodity, X.market_place, X.max_qty, Y.maturity_dt, rank() over 
        (partition by X.commodity, X.market_place order by y.maturity_dt ASC) as rank_val
    FROM  AllData  Y  INNER JOIN X ON Y.qty = X.max_qty   AND   Y.commodity = X.commodity AND Y.market_place = X.market_place
  ),
  BUY  AS
  (
    SELECT
        commodity, market_place, max_qty, maturity_dt,rank_val
    FROM Z
    WHERE rank_val = 1
  ),
   A AS 
  (
    SELECT
        commodity, market_place, max(qty) as max_qty
    FROM    AllData
    WHERE  qty <  0
    group by commodity, market_place
  ),
  B AS
  (
    SELECT
        A.commodity, A.market_place, A.max_qty, Y.maturity_dt, rank() over 
        (partition by A.commodity, A.market_place order by y.maturity_dt ASC) as rank_val
    FROM  AllData  Y  INNER JOIN A ON Y.qty = A.max_qty   AND   Y.commodity = A.commodity AND Y.market_place = A.market_place
  ),
  SELL  AS
  (
    SELECT
        commodity, market_place, max_qty, maturity_dt,rank_val
    FROM B
    WHERE rank_val = 1
  )
  SELECT
    bu.*;sl.*
  FROM  BUY bu INNER JOIN SELL AS sl  ON bu.commodity = sl.commodity
  and bu.market_place = sl.market_place

答案 1 :(得分:0)

不可能,需要先制作一个视图