2014-10-08 59 views
1

我想使用where子句爲下表選擇一些數據。SQL Server R2:使用Where子句選擇語句

create table test 
(
    pid int, 
    pname varchar(10) 
) 

插入一些數據:

insert into test values(1,'Active'); 
insert into test values(1,'DeActive'); 
insert into test values(2,'Active'); 
insert into test values(2,'DeActive'); 
insert into test values(3,'Active'); 
insert into test values(3,'Active'); 
insert into test values(4,'Active'); 
insert into test values(5,'DeActive'); 

現在我想從測試,其中過程的ID pid既有的進程名是Active和顯示數據DeActive

預期結果

pid 
---- 
1 
2 

pid 1和2同時具有進程名pnameActiveDeActive上述過程ID。

回答

4

您可以使用相交,以獲得常規的PID值,請檢查下面的查詢:

Select Distinct pid From Test Where 
pname ='Active' 
Intersect 
Select Distinct pid From Test Where 
pname = 'DeActive' 
+0

非常感謝。 – Meem 2014-10-08 07:02:33

0
select a.pid 
from test a 
join test d on a.pid = d.pid and d.pname = 'DeActive' 
where a.pname = 'Active' 
+1

它會顯示錯誤的歧義列名'pid' – 2014-10-08 06:56:29

+0

我添加了a,雖然它可能是b。以及。 – 2014-10-08 06:58:11

0

這是一個沒有任何硬編碼值和可編輯數字「1」,未來pnames

select distinct pid from (select pid,count(distinct pname) as cnt 
from test 
group by pid) tab 
where cnt>1 
0
SELECT 
    a.pid 
FROM 
    dbo.test a 
join 
    dbo.test b on a.pid = b.pid 
    and a.pname = 'Active' and b.pname = 'DeActive' 
+0

添加一些解釋! – 2014-10-08 07:20:41

+0

這是一個自我連接的表測試,以實現本來是兩張表的。如果你有一個表T1爲(pid,'activate),第二個表T2爲(pid,'deactivate'),可以這樣想。那麼幾乎任何人都會做T1 JOIN T2 ON謂詞的pid。在上面的查詢中,別名「a」和別名「b」表示相同的關係。 – sqlwithpanks 2016-07-08 09:48:44

1
select distinct a.pid 
    from test a 
    join test b on a.pname=b.pname 
    where a.pname not in('Deactive') and a.pid < 3 
0

怎麼樣這...

Select Pid from 
(
select pid , Count (distinct pname) as Pnamecount from test as a 
group by pid 
having COUNT(*) > 1 
) as temp 
Where temp.Pnamecount != 1