sql查询,选择只有一个值的数据

时间:2013-06-06 14:25:37

标签: sql sql-server sql-server-2008

我正在尝试使用此查询来仅获取具有唯一区域= 200的rtp.releaseid

select rtp.ReleaseId, rtp.TerritoryId  from ReleaseTerritoryPrice rtp where 
rtp.TerritoryId=200 

但是我想有些东西不见了,请你帮忙。 谢谢。

4 个答案:

答案 0 :(得分:3)

您可以在WHERE子句中使用以下NOT EXISTS

select rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
where rtp1.territoryId = 200
  and not exists (select releaseId
                  from ReleaseTerritoryPrice t2
                  where t2.territoryId <> 200
                    and rtp1.releaseId = t2.releaseId);

请参阅SQL Fiddle with Demo

或者您可以在WHERE子句中使用NOT IN

select rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
where rtp1.territoryId = 200
  and rtp1.releaseId not in (select releaseId
                              from ReleaseTerritoryPrice t2
                              where t2.territoryId <> 200);

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

有两种方式

SELECT ReleaseId
FROM   ReleaseTerritoryPrice
WHERE  TerritoryId = 200 
EXCEPT
SELECT ReleaseId
FROM   ReleaseTerritoryPrice
WHERE  TerritoryId IS NULL OR TerritoryId <> 200 

或者

SELECT ReleaseId
FROM   ReleaseTerritoryPrice
GROUP BY ReleaseId
HAVING COUNT(DISTINCT TerritoryId) =1 AND MAX(TerritoryId )=200

答案 2 :(得分:0)

也许你的意思是

SELECT MAIN.* FROM ReleaseTerritoryPrice MAIN
WHERE MAIN.ReleaseId in (
    SELECT rtp.ReleaseId
    FROM   ReleaseTerritoryPrice rtp
    WHERE rtp.TerritoryId =200
    GROUP BY rtp.ReleaseId
    HAVING COUNT(rtp.TerritoryId) =1 )

答案 3 :(得分:-1)

使用DISTINCT关键字。

select DISTINCT rtp.ReleaseId, 
     rtp.TerritoryId  
from ReleaseTerritoryPrice rtp 
where rtp.TerritoryId=200