sql查询以获取具有多种条件的数据

时间:2019-03-06 12:08:55

标签: mysql sql sql-server

具有三列的表

A | B | C
1 |11| 0
1 |12| 0
1 |13| 0
2 |33| 5
2 |34| 10
2 |35| 78
5 |45| 0
5 |49| 0
5 |51| 0
8 |10| 0
8 |14| -1
8 |34| -2

我正在寻找SQL查询来获取唯一的A值,该值对于所有B都具有C值ZERO。 (即输出为1和5)

7 个答案:

答案 0 :(得分:0)

您可以:

select t.*
from table t
where t.c = 0 and
      not exists (select 1 from #tm t1 where t1.a = t.a and t1.c < 0) 

答案 1 :(得分:0)

您可以使用group byhaving

select a
from t
group by a
having min(c) = 0 and max(c) = 0;

答案 2 :(得分:0)

您可以检查C的平均值是否为0,然后B的所有C值均为零,

SELECT A 
FROM table
GROUP BY A
HAVING SUM(ABS(C))=0

答案 3 :(得分:0)

使用NOT EXISTS

select distinct a from tablename t
where not exists (
  select 1 from tablename 
  where 
    a = t.a
    and
    c <> 0
)

答案 4 :(得分:0)

尝试这个:

content_id

答案 5 :(得分:0)

尝试一下:

 Select 
 A
 from #tmp
 group by A 
 Having 
 count(*)=count(case when c=0 then 0 else null end)

答案 6 :(得分:0)

对于SQL Server:

SELECT A FROM ta
EXCEPT
SELECT A FROM ta WHERE C <> 0