简体   繁体   中英

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.

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.

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

    -- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM