SQL合并结果和来自工会的计数

时间:2017-07-23 13:09:17

标签: mysql

我有3个表,其中包含操作系统名称,每个表( client1,client2,client3 )都有一个与表名相同的列,其中包含列出操作系统的记录。 像这样

client1 表作为示例

id          client1 <--same column name as the table                                                                                                                 
---------------------
1           Windows XP                                                                                                               
2           Windows Vista                                                                                                            
3           Windows 7 x32                                                                                                            
4           Windows 7 x64
...         ...                                                                                                
16          Not Applicable

当用户选择输入 master 表的结果时,这些表用于填充php下拉列表。

表包含与表( client1,client2,client3 )等名称相同的列,这些列与用户选择填充的此查询无关在php下拉。

表记录示例

client1         client2         client3
----------------------------------------------------------------------------
Windows 10 x64  Not Applicable  Not Applicable  

我希望结果能够全面覆盖操作系统,到目前为止,我在下面的查询中给出了每个表操作系统的计数

SELECT a.client1, COUNT(b.client1)
FROM client1 a 
LEFT JOIN master b ON a.client1 = b.client1
GROUP BY a.client1

UNION ALL(

SELECT c.client2, COUNT(d.client2)
FROM client2 c 
LEFT JOIN master d ON c.client2 = d.client2
GROUP BY c.client2
)
UNION ALL (
SELECT e.client3, COUNT(f.client3)
FROM client3 e 
LEFT JOIN master f ON e.client3 = f.client3
GROUP BY e.client3
)

ORDER by client1 
;

这将返回以下内容(仅显示两个操作系统以节省空间)

client1     COUNT(b.client1)
-----------------------------
Windows 7          1
Windows 7          2
Windows 7          0
Windows 7          0
Windows 7          1
Windows 10         0
Windows 10         0
Windows 10         0
Windows 10         1
Windows 10         1

如何才能获得如下所示返回的结果,以便每个操作系统名称只显示一行,并显示操作系统在表行中的次数

OS                Count
-----------------------------
Windows 7          4
Windows 10         2

1 个答案:

答案 0 :(得分:1)

正确别名3个联合查询中的列。然后从中进行嵌套查询,逐个客户端和SUM计算

SELECT client, SUM(cnt)
FROM
(

    SELECT a.client1 AS client, COUNT(b.client1) AS cnt
    FROM client1 a 
    LEFT JOIN master b ON a.client1 = b.client1
    GROUP BY a.client1

    UNION ALL(

    SELECT c.client2  AS client, COUNT(d.client2) AS cnt
    FROM client2 c 
    LEFT JOIN master d ON c.client2 = d.client2
    GROUP BY c.client2
    )
    UNION ALL (
    SELECT e.client3  AS client, COUNT(f.client3) AS cnt
    FROM client3 e 
    LEFT JOIN master f ON e.client3 = f.client3
    GROUP BY e.client3
    )
) T
GROUP BY client