SQL - 除法和子查询别名

时间:2018-01-10 18:50:10

标签: sql

我正在尝试对某些SQL结果集进行一些计算,并返回满足条件的值(即结果小于0.9的这些计算的行)。在编译时,我得到“每个派生表必须有自己的别名”。

我希望我保持足够简单。

SELECT 1.0*(sum1 - sum2 - sum3)/sum3 AS ratio FROM 
 (SELECT SUM(P.MKT_VAL) AS sum1 FROM PMA_POSITION P WHERE P.EFF_DATE = DATEADD('dd',-1,sysdate) GROUP BY P.ACCT_CD),
 (SELECT SUM(T.EXEC_AMT) AS sum2 FROM PMA_TRANSACTION T WHERE T.TRADE_DATE < DATEADD('dd',-1,sysdate) AND T.TRADE_DATE > DATEADD('dd',-DAY(sysdate)-1,sysdate) AND T.TXN_TYP_CD = 'CASH' GROUP BY T.ACCT_CD),
 (SELECT SUM(P.MKT_VAL) AS sum3 FROM PMA_POSITION P WHERE P.EFF_DATE = DATEADD('dd',-DAY(sysdate)-1,sysdate) GROUP BY P.ACCT_CD) 
WHERE ratio>0.9

1 个答案:

答案 0 :(得分:0)

只需添加别名和JOIN条件

即可
SELECT *
FROM
(
  SELECT 1.0*(sum1 - sum2 - sum3)/sum3 AS ratio 
  FROM 
  (
      SELECT ACCT_CD, 
             SUM(P.MKT_VAL) AS sum1 
      FROM PMA_POSITION P 
      WHERE P.EFF_DATE = DATEADD('dd',-1,sysdate) 
      GROUP BY P.ACCT_CD
  ) t1
  JOIN (
      SELECT ACCT_CD, 
             SUM(T.EXEC_AMT) AS sum2 
      FROM PMA_TRANSACTION T 
      WHERE T.TRADE_DATE < DATEADD('dd',-1,sysdate) AND 
            T.TRADE_DATE > DATEADD('dd',-DAY(sysdate)-1,sysdate) AND 
            T.TXN_TYP_CD = 'CASH' 
      GROUP BY T.ACCT_CD
  ) t2 ON t1.ACCT_CD = t2.ACCT_CD
  JOIN (
      SELECT ACCT_CD, 
             SUM(P.MKT_VAL) AS sum3 
      FROM PMA_POSITION P 
      WHERE P.EFF_DATE = DATEADD('dd',-DAY(sysdate)-1,sysdate) 
      GROUP BY P.ACCT_CD
  ) t3  ON t2.ACCT_CD = t3.ACCT_CD
) t
WHERE t.ratio>0.9