Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do this in one Mysql query?

Tags:

php

mysql

I have a table with two columns:

column A    column B
  1             2
  1             2 
  2             1

I want to return total of ones = 3 total of twos = 3

The best I can come up with is two queries like so:

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 one query? Thanks

like image 304
bsandrabr Avatar asked Apr 02 '10 22:04

bsandrabr


2 Answers

You didn't specify if you want to do this as 2 rows or as 2 values in a row.

Two rows are somewhat obvious (just union together all the values from each columns, and count(1) group by value against the result of the union; so I'll assume you want to do one row.

If you only have 1s or 2s, it's simple:

SELECT SUM(A+B-2) 'twos', SUM(4-A-B) 'ones' FROM myTable
like image 135
DVK Avatar answered Oct 09 '22 08:10

DVK


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;

C.

like image 32
symcbean Avatar answered Oct 09 '22 10:10

symcbean