Can I do this in a single mysql query?

I have a table with two columns:

column A column B 1 2 1 2 2 1 

I want to return the total number of them = 3 only two = 3

The best I can think of is two queries:

 SELECT sum(CASE WHEN columnA =1 THEN 1 ELSE 0 END ) + sum(CASE WHEN columnB =1 THEN 1 ELSE 0 END ) SELECT sum(CASE WHEN columnA =2 THEN 1 ELSE 0 END ) + sum(CASE WHEN columnB =2 THEN 1 ELSE 0 END ) 

Can this be done in a single request? thanks

+6
php mysql
source share
5 answers
 SELECT SUM(IF(columnA=1, 1, 0) + IF(columnB=1, 1, 0)) as ones, SUM(IF(columnA=2, 1, 0) + IF(columnB=2, 1, 0)) as twos FROM myTable; 

FROM.

+1
source share

You did not indicate whether you want to do this as 2 rows or as 2 values ​​in a row.

The two rows are somewhat obvious (just combine all the values ​​from each column and count (1) by value from the result of the join, so I assume that you want to make one row.

If you have only 1 or 2, simply:

 SELECT SUM(A+B-2) 'twos', SUM(4-AB) 'ones' FROM myTable 
+2
source share

To get everything in one request, I would try something like this.

 SELECT Result.Val, COUNT(Result.Val) AS Count FROM ( SELECT ColumnA AS Val FROM TableName UNION SELECT ColumnB AS Val FROM TableName ) AS Result GROUP BY Result.Val 
0
source share

In general, you will consider such things:

 SELECT columnA, COUNT(*) FROM myTable GROUP BY columnA 

to get the counter of all the different values ​​in column A.

-one
source share
 SELECT COUNT(*) FROM table WHERE columnA=1 or columnB=1 
-one
source share

All Articles