SUM a pair of COUNTs from two tables based on a ti

2019-05-08 16:33发布

问题:

Been searching for an answer to this for the better part of an hour without much luck. I have two regional tables laid out with the same column names and I can put out a result list for either table based on the following query (swap Table2 for Table1):

SELECT Table1.YEAR, FORMAT(COUNT(Table1.id),0) AS Total
FROM Table1
WHERE Table1.variable='Y' 
GROUP BY Table1.YEAR

Ideally I'd like to get a result that gives me a total sum of the counts by year, so instead of:

|     REGION 1     |     |     REGION 2     |
|  YEAR  |  Total  |     |  YEAR  |  Total  |
|  2010  |    5    |     |  2010  |    1    |
|  2009  |    2    |     |  2009  |    3    |
|        |         |     |  2008  |    4    |

I'd have:

|     MERGED       |
|  YEAR  |  Total  |
|  2010  |    6    |
|  2009  |    5    |
|  2008  |    4    |

I've tried a variety of JOINs and other ideas but I think I'm caught up on the SUM and COUNT issue. Any help would be appreciated, thanks!

回答1:

SELECT `YEAR`, FORMAT(SUM(`count`), 0) AS `Total`
FROM (
    SELECT `Table1`.`YEAR`, COUNT(*) AS `count`
    WHERE `Table1`.`variable` = 'Y'
    GROUP BY `Table1`.`YEAR`
    UNION ALL
    SELECT `Table2`.`YEAR`, COUNT(*) AS `count`
    WHERE `Table2`.`variable` = 'Y'
    GROUP BY `Table2`.`YEAR`
) AS `union`
GROUP BY `YEAR`


回答2:

You should use an UNION:

SELECT
    t.YEAR,
    COUNT(*) as TOTAL
FROM (

SELECT *
FROM Table1

UNION ALL

SELECT *
FROM Table2

) t
WHERE t.variable='Y'
GROUP BY t.YEAR;


回答3:

Select year, sum(counts) from (
SELECT Table1.YEAR, FORMAT(COUNT(Table1.id),0) AS Total
FROM Table1
WHERE Table1.variable='Y' 
GROUP BY Table1.YEAR
UNION ALL
SELECT Table2.YEAR, FORMAT(COUNT(Table2.id),0) AS Total
FROM Table2
WHERE Table2.variable='Y' 
GROUP BY Table2.YEAR ) GROUP BY year


标签: mysql sum