0

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.

Can someone tell me how to do this? Thanks

4

3 回答 3

0

如果您在父表中的每一行的测试表中可能有很多行,并且测试表上的连接键被索引,那么将查询构造为最有效的方法可能是:

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 将始终为 0 或 1。

如果测试和父表之间的行比小于大约 10:1 ,并且我想对父表中的所有行运行此操作,那么我只需将两个表连接在一起,如 StevieG 的回答

于 2013-11-08T16:25:53.457 回答
0
    -- 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
于 2013-11-08T16:36:58.017 回答
0
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
于 2013-11-08T16:01:06.597 回答