Question

I have 2 tables, table names are case and party. Both tables have case_id. They have a 1 to many relationship (1 case has several parties). For each case, at least one party has to be marked as the primary party (a yes/no field in the party table). I need to find the cases where NO party has been assigned on a case.

So far, I have this query but it only pulls the parties that are not primary parties on each case – but what I need it to find ONLY cases that have NO primary party designated. (I also have a constraint on the type of cases). I am using SQL Server 2008R2. Thanks in advance for any help!

select 
    [case].case_id, [case].case_number, count(party.case_id)as party_count
from 
    party
join 
    [case] on [case].case_id = party.case_id
where 
    [case].case_type_id IN(12,13,15) 
    and party.primary_party = ''
group by 
    [case].case_id, [case].case_number
Was it helpful?

Solution

Try this:

select *
from case C
left join P on P.case_id = C.case_id and P.primary_party != ''
where P.case_id is null

This selects all cases that do not have an associated non-empty primary party.

As a side note, I would recommend using null to represent "no primary party" rather than an empty string.

OTHER TIPS

Although your code is a bit confusing a must say (it's not a very good idea to use SQL reserved words as table or field names, or any other objects i must say, even if you put them on brackets)

But here is the thing you need a RIGHT OUTER JOIN.

It should be something like this:

SELECT
  C.case_id, 
  C.case_number, 
  COUNT(P.case_id) AS party_count
FROM
  party P
  RIGHT OUTER JOIN [case] C ON 
    C.case_id = p.case_id AND
    C.case_type_id IN (12, 13, 15) 
WHERE 
  P.primary_party = '' AND
  P.case_id IS NULL
GROUP BY
  C.case_id, 
  C.case_number
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top