[英]Oracle SQL View Column value 1 if count > n
i am trying to build a view that should look like this: 我试图建立一个应该看起来像这样的视图:
CREATE OR REPLACE VIEW TestView AS
SELECT
p.name,
?? (select count(*) from Test t where t.currentstate in ('Running', 'Ended') and t.ref = p.key) as HasValues
from ParentTable p
I want the column HasValues to bei either 1 or 0. 1 if the count on the current state is > 0. 我想将HasValues列设为1或0。如果当前状态的计数大于0,则返回1。
Can someone tell me how to do this? 有人可以告诉我该怎么做吗? Thanks
谢谢
CREATE OR REPLACE VIEW TestView AS
SELECT
p.name,
case
when nvl(t.mycount,0) > 0 then '1'
else '0'
end HasValues
from ParentTable p
left outer join (select ref, count(*) mycount from Test group by ref) t on t.ref = p.key
If you potentially have a great many rows in the Test table for each row in the parenttable and the join key on the test table is indexed then it may be most efficient to construct the query as: 如果对于父表中的每一行,测试表中可能有很多行,并且索引了测试表上的连接键,则将查询构造为以下方式可能是最有效的:
CREATE OR REPLACE VIEW TestView AS
SELECT
p.name,
(select count(*)
from Test t
where t.currentstate in ('Running', 'Ended') and
t.ref = p.key and
rownum = 1) as HasValues
from ParentTable p;
HasValues will always be 0 or 1 for this query. 对于此查询,HasValues将始终为0或1。
If the ratio of rows between test and the parent table was less than about 10:1 and I wanted to run this for all the rows in the parenttable then I'd just join the two tables together as in StevieG's answer 如果测试表和父表之间的行比小于10:1, 并且我想对父表中的所有行运行该比率,那么我将按照StevieG的答案将两个表连接在一起
-- This has the added advantage that it doesn't count all records,
-- it only needs to see one.
CREATE OR REPLACE VIEW testview
AS
SELECT p.name
, CASE
WHEN EXISTS
(SELECT NULL
FROM test t
WHERE t.currentstate IN ('Running', 'Ended')
AND t.REF = p.key)
THEN
1
ELSE
0
END
hasvalues
FROM parenttable p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.