从条件为

时间:2018-05-28 07:37:31

标签: mysql

我有下面提到的表:

ID     Value
KA-1   A
KA-1   B
KA-1   C
KA-1   D
KA-2   A
KA-2   C
KA-2   C
KA-2   D
KA-3   C
KA-3   B

我想要抓取那些ID,其中至少有一个与D对应的值,但相同的ID不具有值B

必需输出:

ID
KA-2

3 个答案:

答案 0 :(得分:2)

一个简单的解决方案是:

select distinct id from table
   where value='D' and id not in (select distinct id from table where value='B')

答案 1 :(得分:2)

pd.merge(*map(
      lambda x: x.rename(columns={'B':'f','C':'d'}), (df1, df2)
   ), on='A', how='outer', suffixes=('_M', '_B')
).fillna(0)

   A   f_M  d_M   f_B  d_B
0  a  10.0  2.0  34.0  1.0
1  b  20.0  5.0  21.0  5.0
2  c  30.0  3.0   0.0  0.0
3  d   0.0  0.0  45.0  5.0

查看有效的DEMO on SQL Fiddle

答案 2 :(得分:1)

您可以尝试使用exists而不存在:

select id 
from table1 as a
where exists (select *
              from table1 b
              where b.value='D' and b.id=a.id)
      and not exists (select *
              from table1 c
              where c.value='B' and c.id=a.id)