在mySQL中汇总多个相同的表

时间:2016-10-23 22:03:29

标签: mysql count sum

我有4张相同的桌子(每个季度一张)。我已设法计算每个季度的起始终端的每个起始终端和组。但是,我想总结所有4个季度(表格)来得到一些计数。

SELECT StartTerminal, COUNT(*)
FROM test.2013_q1
GROUP BY StartTerminal;

Click here to see screenshot

以下是我尝试过但失败的脚本:

SELECT StartTerminal, COUNT(*) as TotalCount
FROM (
    SELECT StartTerminal
    FROM test.2013_q1
    GROUP BY StartTerminal
    UNION ALL
        SELECT StartTerminal
        FROM test.2013_q2
        GROUP BY StartTerminal
    )
    GROUP BY StartTerminal;

谢谢!

3 个答案:

答案 0 :(得分:0)

我认为错误可能是您没有为您的子查询指定名称。请试试这个 -

SELECT StartTerminal, SUM(count) as TotalCount
FROM (
SELECT StartTerminal, COUNT(*) as count
FROM test.2013_q1
GROUP BY StartTerminal
UNION ALL
SELECT StartTerminal, COUNT(*) as count
FROM test.2013_q2
GROUP BY StartTerminal
) all_year_data
GROUP BY StartTerminal;

答案 1 :(得分:0)

您需要对计算的值使用SUM(),而不是已经分组的值COUNT()

SELECT StartTerminal, SUM(cnt) as TotalCount FROM 
    (SELECT StartTerminal, COUNT(*) AS cnt FROM test.2013_q1 GROUP BY StartTerminal
UNION ALL
    SELECT StartTerminal, COUNT(*) AS cnt FROM test.2013_q2 GROUP BY StartTerminal) AS counted
GROUP BY StartTerminal

答案 2 :(得分:0)

有两种方法可以使您的查询有效: 首先,您可以计算每个表中的条目,然后总结结果:

SELECT StartTerminal, SUM(q_count) FROM
(
SELECT StartTerminal, COUNT(*) AS q_count FROM test.2013_q1 GROUP BY StartTerminal
UNION ALL
SELECT StartTerminal, COUNT(*) AS q_count FROM test.2013_q2 GROUP BY StartTerminal
UNION ALL
SELECT StartTerminal, COUNT(*) AS q_count FROM test.2013_q3 GROUP BY StartTerminal
UNION ALL
SELECT StartTerminal, COUNT(*) AS q_count FROM test.2013_q4 GROUP BY StartTerminal
) as foo
GROUP BY StartTerminal

或者您可以从所有表中选择所有条目(不在子查询中进行分组!)然后再计数:

SELECT StartTerminal, COUNT(*) as TotalCount
FROM (
SELECT StartTerminal FROM test.2013_q1
UNION ALL
SELECT StartTerminal FROM test.2013_q2
UNION ALL
SELECT StartTerminal FROM test.2013_q3
UNION ALL
SELECT StartTerminal FROM test.2013_q4
) as foo
GROUP BY StartTerminal;