2012-04-06 82 views
0

舉個例子,如果我有一個表中的行標識:SQL查詢來獲取基於另一列

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的所有Section Ids。在上面的例子中,SQL應該返回1000和1200(未1100 ATLEAST 1項不是0或-1)

+0

你想有部分IDS誰只有0細節ID或-1,而不是任何其他detailid結果集? – Brian 2012-04-06 19:40:32

+0

@Brian是的,沒錯。 – DotnetDude 2012-04-06 19:43:50

回答

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 
+0

爲什麼'<= 0'?我想我們可以簡單地做一個'MAX(DetailID)= 0和MIN(DetailID)= -1'吧? – DotnetDude 2012-04-06 19:52:30

+0

不可以。您的'1200'示例將MAX和MIN都設爲0。 – 2012-04-06 19:53:24

0
select sectionId from mytable where detailId in (0,-1) 
and section id not in (select sectionid from mytable where detail_id > 0)