如何通过他的州选择不同的数字

时间:2017-04-03 19:44:22

标签: sql postgresql

有这样的表:

create table test(num integer,state text,col1 integer);

和样本数据:

insert into test(num,state,col1) values(1234,'done',1),(1234,'done',2),(1234,'done',11),
(23123,'done',1),(23123,'notdone',1),(23123,'any_other_states',2131);

希望从此表中选择不同的num,其中仅进行状态,例如输出必须为:1234 我尝试这样的事情:

SELECT DISTINCT num
FROM test
WHERE state = 'done' and state not in('notdone','any_other_states')
GROUP BY num;

但输出是1234和23123.怎么做?

2 个答案:

答案 0 :(得分:3)

在Postgresql中:

select num
from test
group by num
having bool_and(state = 'done')

https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE

答案 1 :(得分:1)

你应该在notdone和any_othe_status

中排除num
  SELECT DISTINCT num
  FROM test
  WHERE state = 'done' and num not in 
  ( 
    select num 
    from test 
    where state in ('notdone','any_other_states')

  )