Reputation: 373
I am not so good at SQL, so I have the following tables
Stuff
and
Specialty
Let's say, the worker with name 'Bob' has two specialties. How could I get the specialty table with an extra column (let's say count) which has 1 if the record exists in Stuff and 0 otherwise.
I would like to ask if there is any way to cast a query that returns a result for Bob as shown below?
Any suggestions would be very helpful. Thank you in advance. (I am not sure about the title. Please do suggest if you have a better idea!)
Upvotes: 0
Views: 115
Reputation: 93724
Use Left Outer join
with Null
check. Try this.
SELECT sp.specialitycode,
sp.description,
CASE
WHEN st.specialitycode IS NULL THEN 0
ELSE 1
END AS count
FROM speciality sp
LEFT OUTER JOIN (SELECT specialitycode
FROM stuff
WHERE surname = 'Bob') st
ON sp.specialitycode = st.specialitycode
Upvotes: 1
Reputation: 1269953
I would be inclined to do this with a case
and exists
:
select sp.*,
(case when exists (select 1
from stuff s
where s.surname = 'Bob' and
s.speciality_code = sp.speciality_code
)
then 1 else 0
end) as BobHas
from specialty sp;
Upvotes: 2