简体   繁体   中英

SQL Query to get IDs of rows based on another column

As an example, if I have a table:

DECLARE @tmpTable TABLE
( SectionID INT,
  DetailID INT)

I have the following data:

SectionID    DetailID
1000          -1
1000           0
1000          -1
1100          5000
1100          0
1200          0
1200          0
1300          7000
1300          8000

How do I write the SQL to get all Section Ids that have ALL Detail IDs of 0 or -1. In the above example, the SQL should return 1000 and 1200 (not 1100 as atleast 1 item is not a 0 or a -1)

SELECT DISTINCT SectionID
FROM @tmpTable AS t
WHERE NOT EXISTS
      ( SELECT *
        FROM @tmpTable AS tt
        WHERE tt.SectionID = t.SectionID
          AND tt.DetailID NOT IN (-1, 0)
      )

I think this should work too, since DetailID is an integer and the values you are checking ( -1 and 0 ) have no gaps between them. And it could be faster, with an index on (SectionID, DetailID) :

SELECT SectionID
FROM @tmpTable AS t
GROUP BY SectionID
HAVING MAX(DetailID) <= 0
   AND MIN(DetailID) >= -1
select sectionId from mytable where detailId in (0,-1)
and section id not in (select sectionid from mytable where detail_id > 0)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM