I have a table that contains IDs from two other tables. Those are two integer numbers.
CustomerId SectionId
====================
1 1
1 2
1 3
2 2
2 3
3 1
3 2
3 3
4 2
4 3
What I am looking for is for those records that have the SectionId=1 missing. For the above example I need to retrieve CustomerId 2 and 4.
I cannot do a Select customer ID where SectionId <> 1 because it will bring me all records (1 to 4). I specifically need those that, independently of which SectionId they have, are missing SectionId=1
Thanks.
You need NOT EXISTS
:
SELECT DISTINCT t1.CustomerId
FROM tablename t1
WHERE NOT EXISTS (SELECT 1 FROM tablename t2 WHERE t2.CustomerId = t1.CustomerId AND t2.SectionId = 1)
Or, with conditional aggregation:
SELECT CustomerId
FROM tablename
GROUP BY CustomerId
HAVING COUNT(CASE WHEN SectionId = 1 THEN 1 END) = 0
Try this
select distinct id
from Test
where id not in (
select distinct id
from Test
where section = 1
);
check 2 examples
Declare @t Table (CustomerId int, SectionId int)
insert into @t Values
(1, 1),
(1, 2),
(1, 3),
(2, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3),
(4, 2),
(4, 3)
select DISTINCT CustomerId from @t
where CustomerId not in (
select CustomerId from @t
where SectionId = 1
group by CustomerId
)
SELECT DISTINCT t1.CustomerId
FROM @t t1
WHERE NOT EXISTS (SELECT * FROM @t t2
WHERE t2.CustomerId = t1.CustomerId AND t2.SectionId = 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.