0

例如,如果我有一张桌子:

DECLARE @tmpTable TABLE
( SectionID INT,
  DetailID INT)

我有以下数据:

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

如何编写 SQL 以获取所有详细 ID 为 0 或 -1 的所有部分 ID。在上面的示例中,SQL 应该返回 1000 和 1200(不是 1100,因为至少 1 项不是 0 或 -1)

4

2 回答 2

3
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)
      )

我认为这也应该有效,因为DetailID它是一个整数,并且您正在检查的值 (-10) 之间没有间隙。它可能会更快,有一个索引(SectionID, DetailID)

SELECT SectionID
FROM @tmpTable AS t
GROUP BY SectionID
HAVING MAX(DetailID) <= 0
   AND MIN(DetailID) >= -1
于 2012-04-06T19:44:07.947 回答
0
select sectionId from mytable where detailId in (0,-1)
and section id not in (select sectionid from mytable where detail_id > 0)
于 2012-04-06T19:40:24.683 回答