简体   繁体   中英

Select query which give those rows having two or more than two non-zero values

I have a MySQL table with 8 columns (id,user,a,b,c,d,e,f) in which I have a list of distinct users with (0 through 9) values in columns like this:

Id  User    A   B   C   D   E   F
1   0001    0   1   0   0   0   0
2   0002    0   5   8   4   6   5
3   0003    0   0   0   0   0   5
4   0004    2   6   4   5   4   1
5   0005    1   0   0   0   0   0
6   0006    7   6   5   4   0   9
7   0007    4   0   0   0   0   8]

I want a MySQL select query which gives a list of those users having two or more than two non-zero values. So the query should return record id (2,4,6,7). Thanks

Here is another way to do so

select *
from t
where
( 
  (A <> 0 )+
  (B <> 0) +
  (C <> 0 )+
  (D <> 0 )+
  (E <> 0 )+
  (F <> 0 ) 
) >= 2

Not equal to operator returns boolean(0/1) value against the criteria and you can sum up the results for each column and eliminate the records according to your criteria

DEMO

Try this.

select user  
from (
SELECT *,
       CASE WHEN a>0 THEN 1 ELSE 0 END + 
       CASE WHEN b>0 THEN 1 ELSE 0 END + 
       CASE WHEN c>0 THEN 1 ELSE 0 END + 
       CASE WHEN d>0 THEN 1 ELSE 0 END + 
       CASE WHEN e>0 THEN 1 ELSE 0 END + 
       CASE WHEN f>0 THEN 1 ELSE 0 END chk
FROM   yourtable 
) a 
where chk>=2

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