Oracle SQL:如何将总列添加到结果集中?

时间:2016-02-23 19:42:18

标签: sql oracle

我有以下查询:

WITH
  curr AS ( 
    SELECT COUNT(*)
    FROM   table1  
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  ),
  hist AS (
    SELECT COUNT(*)
    FROM   table2 
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  )
SELECT (curr+hist) FROM dual;

现在此查询不起作用,因为currhist是无效的标识符,但我想将两个结果合并为一个总数并返回该结果。怎么可以这样做?

1 个答案:

答案 0 :(得分:1)

您需要在SELECT中引用两个CTE。像

这样的东西
WITH
  curr AS ( 
    SELECT COUNT(*) cnt
    FROM   table1  
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  ),
  hist AS (
    SELECT COUNT(*) cnt
    FROM   table2 
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  )
SELECT curr.cnt + hist.cnt
  FROM curr
       CROSS JOIN hist

会奏效。

WITH
  curr AS ( 
    SELECT COUNT(*) cnt
    FROM   table1  
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  ),
  hist AS (
    SELECT COUNT(*) cnt
    FROM   table2 
    WHERE column1 LIKE 'A%'
    AND column2 = TRUNC(CURRENT_TIMESTAMP)
  )
SELECT SUM(cnt)
  FROM (SELECT curr.cnt FROM curr
        UNION ALL
        SELECT hist.cnt FROM hist)