Reputation: 548
We need to create a view that combines both these SQL statements together.
SELECT g.state_cd, g.state_name,
case when s.ROLE_ID = 110 then 'Yes' else 'No' end POC
FROM us_state g
LEFT OUTER JOIN role s ON g.state_cd = s.OFC_STATE_CD
and s.role_id = 110
SELECT g.state_cd, g.state_name,
case when s.ROLE_ID = 120 then 'Yes' else 'No' end ADM
FROM us_state g
LEFT OUTER JOIN role s ON g.state_cd = s.OFC_STATE_CD
and s.role_id = 120
Eg.
An user will have multiple rows. Some users will have role = 110 & some users will have role = 120 & some will have a combination of both. So is it possible to create 1 SQL statement that combines both of these. The result should be:
MD Maryland Yes No
NY Newyork No Yes
NJ Newhersey Yes Yes
The above table implies:
MD user has only role of 110
NY user has only the role of 120
NJ user has both roles.
Hope I'm clear on what is needed & it makes sense.
I tried to combine them like this:
SELECT g.state_cd, g.state_name,
case when s.ROLE_ID = 110 then 'Yes' else 'No' end POC,
case when s.ROLE_ID = 120 then 'Yes' else 'No' end ADM
FROM us_state g
LEFT OUTER JOIN role s ON g.state_cd = s.OFC_STATE_CD
and s.role_id in (110, 120)
But this doesn't work and it returns duplicate rows. Not sure what I'm missing here. I would appreciate it greatly if someone can help.
Thanks
Harish
Upvotes: 1
Views: 631
Reputation: 8423
This is also a variation:
select state_cd, state_name
,case when (select count(*) from role r1
where r1.ofc_state_cd = s.state_cd
and r1.role_id = 110) > 0 then 'YES' else 'NO'
end as POC
,case when (select count(*) from role r2
where r2.ofc_state_cd = s.state_cd
and r2.role_id = 120) > 0 then 'YES' else 'NO'
end as ADM
from us_state s;
http://sqlfiddle.com/#!4/161e7/8
Upvotes: 2
Reputation: 1269753
You need to aggregate the results:
SELECT g.state_cd, g.state_name,
max(case when s.ROLE_ID = 110 then 'Yes' else 'No' end) as POC,
max(case when s.ROLE_ID = 120 then 'Yes' else 'No' end) as ADM
FROM us_state g LEFT OUTER JOIN
role s ON g.state_cd = s.OFC_STATE_CD and s.role_id in (110, 120)
group by g.state_cd, g.state_name
It turns out that "Yes" and "No" work well with MAX.
Upvotes: 3