oracle 创建包含多个子查询的SQL视图

anauzrmj  于 2023-08-03  发布在  Oracle
关注(0)|答案(2)|浏览(106)

我有一个简单的查询,它工作得很好:

(select distinct ACTIVE_MEMBERS, BRANCH_MEMBERS from
    ( select count(*) from pink_floyd pf ) as ACTIVE_MEMBERS,
    ( select count(*) from pink_floyd pf ) as BRANCH_MEMBERS
);

字符串
从上面的查询,我想创建视图-我这样做:

create or replace view v_monthly_data AS
select data.active_members, data.branch_members
from (select distinct ACTIVE_MEMBERS, BRANCH_MEMBERS from
    ( select count(*) from pink_floyd pf ) as ACTIVE_MEMBERS,
    ( select count(*) from pink_floyd pf ) as BRANCH_MEMBERS
) as data;


但它似乎是不正确的。我会很感激你解释我创建这个视图的正确方法。此外,我不希望创建多个视图,然后加入它们。

u4vypkhs

u4vypkhs1#

您的简单查询不是有效的Oracle语法,因为AS不是表(或内联视图)别名前的有效关键字。您似乎希望使用列别名而不是表别名。
正确的查询应该是:

select distinct ACTIVE_MEMBERS, BRANCH_MEMBERS
from   ( select count(*) as ACTIVE_MEMBERS from pink_floyd pf ),
       ( select count(*) as BRANCH_MEMBERS from pink_floyd pf );

字符串
可以简化为:

select count(*) AS active_mambers,
       count(*) AS branch_members
from   pink_floyd;


然后,您可以创建一个视图:

CREATE VIEW v_monthly_data (active_members, branch_members) AS
select count(*),
       count(*)
from   pink_floyd;


或者是

CREATE VIEW v_monthly_data AS
select count(*) AS active_members,
       count(*) AS branch_members
from   pink_floyd;

hof1towb

hof1towb2#

你想多了
由于两个查询都返回标量值,因此可以将它们用作列

CREATE TABLE pink_floyd (id int)
create or replace view v_monthly_data AS
select 
    ( select count(*) from pink_floyd pf ) as ACTIVE_MEMBERS,
    ( select count(*) from pink_floyd pf ) as BRANCH_MEMBERS
  FROM DUAL
;
SELECT * FROM v_monthly_data

| 分支机构_会员| BRANCH_MEMBERS |
| --| ------------ |
| 0个| 0 |
fiddle
如果有多个返回行,则需要类似于

CREATE TABLE pink_floyd (id int)
create or replace view v_monthly_data AS
select AM.count_  ACTIVE_MEMBERS
  , BM.COUNT_  BRANCH_MEMBERS
  FROM
    ( select id, count(*) count_ from pink_floyd pf GROUP BY id) AM
  JOIN 
   ( select id, count(*) count_  from pink_floyd pf GROUP BY id)  BM
ON AM.id = BM.id
SELECT * FROM v_monthly_data

fiddle

相关问题