0

我有一个表,其中所有数据都按行存储。

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.

以下几行的内容.. 从表中选择计数(值),其中字段 = 'dist' 和值 = 1 和键,名称 在(选择键,名称 从表中字段 = '状态' 和值 =1)

在上面的示例中,我希望答案为“3”(带有 key = 21 的 sam 不符合条件)。

4

3 回答 3

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
)
于 2012-08-27T09:37:55.233 回答
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
于 2012-08-27T09:38:11.263 回答
0

使用连接:

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
于 2012-08-27T09:48:28.923 回答