user3063952
user3063952

Reputation: 97

MySQL query on multiple tables

Greets! I have 12 tables, one for each month of the year:

January

+----+-----+  
| id | sale|  
+----+-----+  
|  1 | 250 |  
|  3 | 500 |
|  5 | 200 |  
|  7 | 100 |  
+----+-----+

February

+----+-----+  
| id | sale|  
+----+-----+  
|  1 | 350 |  
|  2 | 400 |
|  3 | 500 |  
|  4 | 800 |  
+----+-----+

etc.

I need to do a query where the result is something like this:

Annual Sales
+----+-----------+-----------+
| id | Sales_Jan | Sales_Feb |
+----+-----------+-----------+
|  1 |       250 |       350 |
|  2 |         0 |       400 |
|  3 |       500 |       500 |
|  4 |         0 |       800 |
|  5 |       200 |         0 |
|  7 |       100 |         0 |
+----+-----------+-----------+

Where the matching ids from both tables do not duplicate and the missing ids from other months are shown by putting a 0 or any other symbol indicating that there was not any sales that month from that id.

Thank you very much!

Upvotes: 0

Views: 48

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

You can approach this using union all and aggregation:

select id,
       sum(case when month = 'Jan' then sale else 0 end) as Jan_Sale,
       sum(case when month = 'Feb' then sale else 0 end) as Feb_Sale,
       . . .
       sum(case when month = 'Dec' then sale else 0 end) as Dec_Sale
from ((select 'Jan' as month, id, sale from January) union all
      (select 'Feb' as month, id, sale from February) union all
      . . .
      (select 'Dec' as month, id, sale from February)
     ) t
group by id;

Upvotes: 3

Related Questions