Jump to content

Confusing Query Help - Multiple Entries


herghost

Recommended Posts

HI guys

 

I am having some issues getting the results I want from a query.

 

Basically I have two tables. To keep things short and sweet ill use made up values

 

table a contains the field ID,Week

table b contains ID and type

 

Type can be either a 1 or a 0 and and the ID will match table A.

 

Table b can contain more than one entry for the same ID on table A with different types.

 

What I am trying to do is return all the ID's in table B that only contain a type of 0, for a specific week in table a. So if table B contains:

 

ID Type

1 1

1 0

2 0

2 0

3 1

3 1

 

I would only need to return ID 2

 

I have tried something like this

 

select a.id, b.id
from b inner join
a on b.id = a.id
where a.week = '22' and b.type = 0 

 

This issue is that it will return ID 1 and 2 as ID 1 contains a 0?

 

I hope this is clear enough!

 

Thanks for any pointers or help

Link to comment
Share on other sites

Two possible options I can think of, the first being a sub-query for the totals:

http://sqlfiddle.com/#!3/96e2b/3/0

SELECT
  *
FROM tblA
INNER JOIN (SELECT ID, COUNT(*) as rows FROM tblB GROUP BY ID) as total ON tblA.ID=total.ID
INNER JOIN (SELECT ID, Type, COUNT(*) as rows FROM tblB GROUP BY ID, Type) as groupTotal ON tblA.ID=groupTotal.ID
WHERE
  groupTotal.Type=0 
  AND total.rows=groupTotal.rows

 

The second being a query using GROUP BY and a HAVING filter:

http://sqlfiddle.com/#!3/96e2b/6/0

SELECT
  tblA.ID as aid,
  tblB.ID as bid
FROM tblA
INNER JOIN tblB ON tblA.ID=tblB.ID
GROUP BY
  tblA.ID,
  tblB.ID
HAVING
  SUM(CASE WHEN tblB.Type=0 THEN 1 ELSE 0 END)=COUNT(tblB.ID)

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.