Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Obtendo a contagem de 2 tabelas e agrupando por mês


Junte as duas tabelas com o mês:
SELECT MONTH(I.date) AS `month`
     , COUNT(I.ID) AS `countin`
     , COUNT(O.ID) AS `countOUT`
  FROM TableIN I
 LEFT JOIN TableOUT O
    ON MONTH(I.Date) = MONTH(O.Date)
 GROUP BY MONTH(I.date)
UNION
SELECT MONTH(O.date) AS `month`
     , COUNT(I.ID) AS `countin`
     , COUNT(O.ID) AS `countOUT`
  FROM TableIN I
 RIGHT JOIN TableOUT O
    ON MONTH(I.Date) = MONTH(O.Date)
 GROUP BY MONTH(I.date);

Resultado:
| MONTH | COUNTIN | COUNTOUT |
------------------------------
|     5 |       1 |        1 |
|     7 |       1 |        1 |
|     6 |       0 |        1 |

Veja este SQLFiddle


Além disso, para ordenar seu resultado por mês, você precisa usar uma subconsulta como esta:
SELECT * FROM
(
    SELECT MONTH(I.date) AS `month`
         , COUNT(I.ID) AS `countin`
         , COUNT(O.ID) AS `countOUT`
      FROM TableIN I
     LEFT JOIN TableOUT O
        ON MONTH(I.Date) = MONTH(O.Date)
     GROUP BY MONTH(I.date)
    UNION
    SELECT MONTH(O.date) AS `month`
         , COUNT(I.ID) AS `countin`
         , COUNT(O.ID) AS `countOUT`
      FROM TableIN I
     RIGHT JOIN TableOUT O
        ON MONTH(I.Date) = MONTH(O.Date)
     GROUP BY MONTH(I.date)
    ) tbl
ORDER BY Month;

Veja este SQLFiddle