根据时间变量从两个表中求和一对COUNT

时间:2012-07-09 14:58:44

标签: mysql sum

在没有太多运气的情况下,大部分时间都在寻找答案。我有两个区域表,使用相同的列名称,我可以根据以下查询为表格输出结果列表(表1中的交换表2):

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

理想情况下,我希望得到的结果能够按年计算总数,因此不是:

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

我有:

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

我尝试过各种各样的JOIN和其他想法,但我想我已经陷入了SUM和COUNT问题。任何帮助将不胜感激,谢谢!

4 个答案:

答案 0 :(得分:5)

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`

答案 1 :(得分:0)

你应该使用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;

答案 2 :(得分:0)

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

答案 3 :(得分:0)

改进 Shehzad 的回答:

SELECT YEAR, FORMAT(SUM(counts),0) AS total FROM (
SELECT Table1.YEAR, COUNT(Table1.id) AS counts
FROM Table1
WHERE Table1.variable='Y' 
GROUP BY Table1.YEAR
UNION ALL
SELECT Table2.YEAR, COUNT(Table2.id) AS counts
FROM Table2
WHERE Table2.variable='Y' 
GROUP BY Table2.YEAR ) AS newTable GROUP BY YEAR