2012-04-06 86 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)