从多个表中汇总多个计数

时间:2013-10-23 12:01:17

标签: mysql

我有不同的表(每个区域),其中一些列是相同的。现在,我需要计算放在多个表中一列中的每个值。我试图得到一笔钱,所以我不必使用4个单独的查询和输出。此外,这些值与查找表

匹配

地区表 - 表1:

    id       | Column1 | 
    ---------|----------|
    1        | 1
    2        | 2
    3        | 3
etc

查找表

    id       | Description | 
    ---------|-------------|
    1        | Description1
    2        | Description2
    3        | Description3

我用来从1个表中获取计数的查询是:

SELECT Description, Count(*) as Number from Table1, LookupTable 
WHERE Column1 = LookupTable.id GROUP BY Column1 ORDER BY Number Desc

输出

 Description   | Number
---------------|--------
Description1   | Number
Description2   | Number
Etc.

关于如何总结4个表中每个描述/值的计数的任何想法,这些表生成如上所示的输出(但随后是每个描述的总和值)?

2 个答案:

答案 0 :(得分:2)

目前尚不清楚,但我想你可以使用:

select LookupTable.id,LookupTable.Description, SUM(Cnt) as Number 
from LookupTable

JOIN
(
    SELECT Column1 as CId, count(*) as Cnt from Table1 group by Column1
    union all
    SELECT Column2 as CId, count(*) as Cnt from Table2 group by Column2
    union all
    SELECT Column3 as CId, count(*) as Cnt from Table3 group by Column3
    union all
    SELECT Column4 as CId, count(*) as Cnt from Table4 group by Column4
) T1 on LookupTable.id =T1.Cid
 GROUP BY LookupTable.id,LookupTable.Description
 ORDER BY Number Desc

答案 1 :(得分:0)

使用此查询:

SELECT LookupTable.Description, Count(*) as Number 
   FROM Table1, LookupTable 
      WHERE Table1.Column1 = LookupTable.id 
          GROUP BY Table1.Column1;

您已保留表名或其别名以调用该列。