1

我有 4 个从同一个表中获取数据的 SQL 查询,我想知道您是否可以创建一个包含多个查询的视图。例如,其中一个查询类似于:

SELECT Count(COLUMN1) FROM TABLE1 WHERE COLUMN3 > '01-Oct-12' AND COLUMN3< '01-Nov-12' 

而另一个看起来像:

SELECT Count(COLUMN2) FROM TABLE1 WHERE COLUMN3 > '01-Oct-12' AND COLUMN3 < '01-Nov-12' 

谢谢,

一世。

4

3 回答 3

2
CREATE VIEW viewname AS
SELECT Count(COLUMN1) as col1 FROM TABLE1 WHERE COLUMN3 > '01-Oct-12' AND COLUMN3< '01-Nov-12'
union all
SELECT Count(COLUMN2) as col1 FROM TABLE1 WHERE COLUMN3 > '01-Oct-12' AND COLUMN3 < '01-Nov-12' 
于 2012-11-01T12:18:42.913 回答
2

如果您希望数据在同一记录集和同一列中,则可以使用UNION ALL

SELECT Count(COLUMN1) As CNT, 'Q1' as Src
FROM TABLE1 
WHERE COLUMN3 > '01-Oct-12' 
 AND COLUMN3< '01-Nov-12'
UNION ALL
SELECT Count(COLUMN2) as Cnt, 'Q2' as Src
FROM TABLE1 
WHERE COLUMN3 > '01-Oct-12' 
  AND COLUMN3 < '01-Nov-12'

我包括了一列,以帮助您确定您的数据来自哪个查询。如果不需要,那么您可以放弃使用它。

于 2012-11-01T12:18:46.107 回答
1

最简单的实现是:

create or replace view v23 as 
     select count(column1) as col1_count
            , count(column2) as col2_count
     from TABLE1
      WHERE COLUMN3 > '01-Oct-12' AND COLUMN3 < '01-Nov-12' 

但是,如果不是所有查询都使用相同的条件,您可以使用标量子查询:

create or replace view v23 as 
  select 
     (select count(column1) from TABLE1 
        WHERE COLUMN3 > '01-Oct-12' AND COLUMN3 < '01-Nov-12' ) as col1_count 
     , (select count(column2) from TABLE2 
        WHERE COLUMN3 > '01-Oct-12' AND COLUMN3 < '01-Nov-12' ) as col2_count
  from dual   
于 2012-11-01T12:28:11.767 回答