Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get rows where the entire group does NOT have a value

Given a table with grouped data (below), what is a query that selects only values where the entire group does not have a specified value?

Here is my data:

id  firstid lastid  descrip
1   1       2       Y
2   2       3       Y
3   2       4       N
4   2       5       Y
5   3       6       Y
5   3       7       Y
5   4       8       N
5   4       9       N
6   4       10      Y
7   5       11      N
8   5       12      N
9   6       13      Y
10  6       14      Y
11  7       15      Y
12  7       16      N

In this case, I want to get the FirstId of the data where none of the rows with that particular FirstId have a Descrip of Y. E.g., the FirstId 2 has one "Y" in it, and FirstId 7 also has a "Y" in it. So the result should be "5" for this example case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried,

select FirstId, descrip from sampletable
where descrip <> 'Y'
group by FirstId, descrip

>Solution :

set nocount on
declare @sampletable table
(
  id      int
 ,firstid int
 ,lastid  int
 ,descrip nvarchar(1)
)
insert into @sampletable values(1 ,1 ,2 ,'Y')
insert into @sampletable values(2 ,2 ,3 ,'Y')
insert into @sampletable values(3 ,2 ,4 ,'N')
insert into @sampletable values(4 ,2 ,5 ,'Y')
insert into @sampletable values(5 ,3 ,6 ,'Y')
insert into @sampletable values(5 ,3 ,7 ,'Y')
insert into @sampletable values(5 ,4 ,8 ,'N')
insert into @sampletable values(5 ,4 ,9 ,'N')
insert into @sampletable values(6 ,4 ,10,'Y')
insert into @sampletable values(7 ,5 ,11,'N')
insert into @sampletable values(8 ,5 ,12,'N')
insert into @sampletable values(9 ,6 ,13,'Y')
insert into @sampletable values(10,6 ,14,'Y')
insert into @sampletable values(11,7 ,15,'Y')
insert into @sampletable values(12,7 ,16,'N')
--Show FirstIDs where the # of "N" entries is the same as the total # of entries
SELECT ST.FIRSTID
FROM @SAMPLETABLE ST
WHERE ST.DESCRIP = 'N'
GROUP BY ST.FIRSTID, ST.DESCRIP
HAVING COUNT(*) = (
  SELECT COUNT(*) FROM @SAMPLETABLE ST2 WHERE ST2.FIRSTID = ST.FIRSTID
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading