1

我有不同的表(每个区域),其中一些列是相同的。现在我需要对放置在多个表的一列中的每个值进行计数。我正在尝试为此获得总和,因此我不必使用 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 个表中汇总 Column1 的每个描述/值的计数的任何想法(然后是每个描述的总和值)?

4

2 回答 2

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
于 2013-10-23T12:08:43.250 回答
0

使用此查询:

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

您已经留下表的名称或其别名来调用该列。

于 2013-10-23T12:05:57.977 回答