简体   繁体   English

SQL COUNT GROUP BY多个表

[英]SQL COUNT GROUP BY multiple tables

I have 10 + tables that all have a column 'Error Message'. 我有10多个表,每个表都有“错误消息”列。 There is a unique ID for each Error Message. 每个错误消息都有一个唯一的ID。 I need to write a script that returns the top 5 most recurring errors between all tables. 我需要编写一个脚本,该脚本返回所有表之间的前5个最经常发生的错误。 Here is an example of the current structure along with the desired result. 这是当前结构的示例以及所需的结果。

Tables

Table 1
**Error Message        
     Mes 1              
     Mes 2                
     Mes 3                    

Table 2
**Error Message     
     Mes 1
     Mes 2            
     Mes 3               
     Mes 4
     Mes 4 
     Mes 4 
     Mes 4                       

Table 3
**Error Message                         
     Mes 5
     Mes 1                 
     Mes 6
     Mes 2                

Desired Result 所需结果

**Error Message      Error Count**     
     Mes 4                4
     Mes 1                3
     Mes 2                3
     Mes 3                2
     Mes 5                1  
select errMsg, count(*) as errCnt
from
(
    select errMsg from table1
    union all 
    select errMsg from table2
    union all 
    select errMsg from table3
    ...
) tmp
group by errMsg
order by count(*) desc

Depending on your DB engine add either limit 5 or top 5 or ROWNUM <= 5 根据您的数据库引擎,添加limit 5top 5ROWNUM <= 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM