简体   繁体   中英

sql query to get data with multiple condition

table ta having three columns

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

I am looking the SQL query to fetch the distinct A value which is having C value ZERO for all the B . (ie the output would be 1 & 5)

You can use group by and having :

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

You can check the average of C if it is 0 then all the C values are zero for B,

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

试试这个:

select distinct A from [dbo].[table] where A not in ( select A from [dbo].[table] where C <> 0)

You can do :

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) 

With NOT EXISTS :

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

Try this :

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

For SQL Server:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM