在联合查询中按类型计算记录

时间:2018-01-26 21:33:30

标签: sql sqlite union

我有一个带有两个表'消息的sqlite3数据库'和' svd',它们包含类似的信息并共享某些字段,例如message_type,但除此之外还有足够的不同以保证单独的表格。

我想创建一个计算两个表中消息类型数的查询。

这适用于各个表,但在UNION中使用时会产生错误的结果。我不明白出了什么问题,有人能帮忙解释一下吗?

每个表的单个message_type计数:

SELECT message_type AS ID, message_types.type AS Type, count(*) as MsgCount FROM messages
       INNER JOIN message_types ON messages.message_type = message_types.ID
       GROUP BY message_type ORDER BY MsgCount DESC'

这产生了预期的结果:

ID          Type                                                   MsgCount  
----------  -----------------------                                ----------
1           Position Report Class A                                96513     
3           Position Report Class A (Response to interrogation)    46265     
18          Standard Class B CS Position Report                    11098     
11          UTC and Date Response                                  961       
10          UTC and Date Inquiry                                   452 

对于SVD表,这是查询:

SELECT message_type AS ID, message_types.type AS Type, count(*) as MsgCount FROM svd
       INNER JOIN message_types ON svd.message_type = message_types.ID
       GROUP BY message_type ORDER BY MsgCount DESC'

结果:

ID          Type                            MsgCount  
----------  ------------------------------  ----------
5           Static and Voyage Related Data  4746      
24          Static Data Report              3250   

现在UNION代码应该产生一个组合结果,但它没有。查询:

SELECT message_type AS ID, message_types.type AS Type, count(*) as MsgCount FROM messages
       INNER JOIN message_types ON messages.message_type = message_types.ID
UNION
SELECT message_type AS ID, message_types.type AS Type, count(*) as MsgCount FROM svd
       INNER JOIN message_types ON svd.message_type = message_types.ID
GROUP BY message_type ORDER BY MsgCount DESC

导致这个不完整的结果集:

ID          Typee                                                  MsgCount  
----------  -----------------------------------------------------  ----------
1           Position Report Class A                                156063    
5           Static and Voyage Related Data                         4761      
24          Static Data Report                                     3260 

您可以看到消息类型1是消息表,但是5和24来自SVD表。类型1的MsgCount似乎是"消息"中所有消息类型的总和。 table - 所以它确实混合并混合了一些数据,但似乎已经将所有"消息组合在一起#34;表结果为一个计数?

1 个答案:

答案 0 :(得分:1)

您缺少第一个子查询中的group by。我还推荐表别名:

SELECT m.message_type AS ID, mt.type AS Type, count(*) as MsgCount
FROM messages m mt INNER JOIN
     message_types mt
     ON m.message_type = mt.ID
GROUP BY m.message_type AS ID, mt.type AS Type
UNION
SELECT svd.message_type AS ID, mt.type AS Type, count(*) as MsgCount
FROM svd INNER JOIN
     message_types mt
     ON svd.message_type = mt.ID
GROUP BY svd.message_type, mt.type
ORDER BY MsgCount DESC