我有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'
谢谢,
予。
答案 0 :(得分: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'
答案 1 :(得分: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'
我添加了一个列,以帮助您确定数据来自哪个查询。如果不需要,那么您可以放弃使用它。
答案 2 :(得分: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