4

一个小时的大部分时间里一直在寻找这个问题的答案,但运气不佳。我有两个具有相同列名的区域表,我可以根据以下查询为任一表列出结果列表(将表 2 交换为表 1):

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

4 回答 4

7
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`
于 2012-07-09T15:06:56.887 回答
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;
于 2012-07-09T15:04:34.633 回答
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
于 2012-07-09T15:05:09.687 回答
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
于 2021-03-16T02:11:06.020 回答