使用同一张主表中的WHERE子句创建两个不同的列

时间:2019-06-13 16:35:12

标签: oracle-sqldeveloper

我需要从Table_2的同一列(A)中提取两列(B和C)。这两列(下面的脚本)被实现为更大的查询。当我仅使用其中一列(例如仅B)运行查询时,该查询将在几秒钟内运行良好。但是,当我在查询中同时运行B和C时,查询只是继续运行,并且没有结束。我尝试给两列提供不同的别名以查看是否可以解决问题,但是我无法弄清楚为什么查询不同时使用B和C来运行。除了WHERE子句外,这两列几乎相同。

对于B和C列,我在脚本中只有一个联接,类似于:FROM Table_1 T1,Table_2 T2 WHERE T2.ENT_REF = T1.ENT_REF(+)

有什么想法吗?

  ( SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2 
      WHERE T2.ENT_REF = T1.ENT_REF
      AND UPPER(T2.PER) = 'HURR' 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) B,


    (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2 
      WHERE T2.ENT_REFE = T1.ENT_REF 
      AND UPPER(T2.PER) IN ('I', 'II', 'II') 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) C

1 个答案:

答案 0 :(得分:1)

在PL / SQL中需要虚拟表。 (来自双重)

您还需要加入表(table_1)。

请确保每个查询都可以返回您的期望值。

在原始查询中,您输入了“ T2.ENT_REF = T1.ENT_REF”,但未添加table_1。这将导致语法错误。

请尝试以下操作:

SELECT
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REF = T1.ENT_REF
      AND UPPER(T2.PER) = 'HURR' 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) as B,
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REFE = T1.ENT_REF 
      AND UPPER(T2.PER) IN ('I', 'II', 'II') 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) as C
FROM DUAL

更新:

您可以使用[concat]

SELECT
CONCAT(
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REF = T1.ENT_REF
      AND UPPER(T2.PER) = 'HURR' 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) ,
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REFE = T1.ENT_REF 
      AND UPPER(T2.PER) IN ('I', 'II', 'II') 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) 
) AS BandC
FROM DUAL

更新2:

SELECT
(
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REF = T1.ENT_REF
      AND UPPER(T2.PER) = 'HURR' 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) +
  (SELECT  
      SUM(T2.A) as prem
      FROM Table_2 T2, Table_2 T1
      WHERE T2.ENT_REFE = T1.ENT_REF 
      AND UPPER(T2.PER) IN ('I', 'II', 'II') 
      AND UPPER(T2.ENT_TYPE) = 'POL'
      AND T2.Cov NOT IN ('OUTPROP','COV')
  ) 
) AS BandC
FROM DUAL