2012-08-27 15 views
0

我有一張表,其中所有數據都以行方式存儲。「IN」子句中的多個內聯變量

key  name field value 
11  sam state 1 
11  fred state 1 
21  sam state 3 
21  fred state 1 
11  sam dist 1 
11  fred dist 1 
21  sam dist 1 
21  fred dist 1 

我需要一個查詢來獲取"name" having dist = 1 with state = 1的編號。

從表

東西上下面的行.. SELECT COUNT(值) 其中字段= 'DIST' 和值= 1 和鍵,名稱在(從表其中字段選擇鍵,名稱 ='狀態'和值= 1)

在上面的例子中,我希望答案爲「3」(sam with key = 21不符合條件)。

回答

0

試試這個:

select count (value) 
from table a 
where field = 'dist' 
and value = 1 
and exists 
(
    select 1 from table n where field = 'state' and value =1 
    and a.key = b.key 
    and a.name = b.name 
) 
+0

謝謝。在podiluska的解決方案上工作。 – user1606540

0
select count(distinct yourtable.name) 
from yourtable 
inner join 
(
    select key, name from yourtable 
    where field='dist' and value = 1 
) dist1 
    on yourtable.key = dist1.key 
    and yourtable.name = dist1.name 
where field='state' and value = 1 
+0

謝謝。它對我來說非常合適。 – user1606540

0

使用JOIN:

select count(distinct key, name) from table t1 
inner join table t2 
    on t2.key = t1.key and t2.name = t1.name and t2.field = 'state' and t2.value = 1 
where t1.field = 'dist' and t1.value = 1 
+0

謝謝你Guffa。工作在podiluska的解決方案,幫助我。和你的一樣。再一次感謝你。 – user1606540

+0

@ user1606540​​:嗯,這個直接加入表而不是子查詢。 – Guffa