Wisher Well
Wisher Well

Reputation: 133

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

Upvotes: 2

Views: 79

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93724

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

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

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

Upvotes: 4

Related Questions