我的数据库逐行报告了几个装有已安装软件(仅特定软件)的终端。这是一个示例:
HOSTNAME | MAC ADDRESS | IP ADDRESS | SOFTWARE NAME
---------------------------------------------------
PC-AAA | 94-da-r2-12 | xx.xx.xx.xx| TeamViewer
PC-AAA | 94-da-r2-12 | xx.xx.xx.xx| Google Chrome
PC-BBB | 94-da-s4-16 | xx.xx.xx.xx| TeamViewer
PC-BBB | 94-da-s4-16 | xx.xx.xx.xx| Google Chrome
etc.
如何构建查询以使每个软件都有一个列,如以下示例所示?
HOSTNAME | MAC ADDRESS | IP ADDRESS | TeamViewer | Google Chrome
----------------------------------------------------------------
PC-AAA | 94-da-r2-12 | xx.xx.xx.xx| TeamViewer |
PC-AAA | 94-da-r2-12 | xx.xx.xx.xx| | Google Chrome
PC-BBB | 94-da-s4-16 | xx.xx.xx.xx| TeamViewer |
PC-BBB | 94-da-s4-16 | xx.xx.xx.xx| | Google Chrome
答案 0 :(得分:0)
这是枢纽SQL查询的方法... SQL Server支持数据透视,而MySQL不支持
如果软件数量固定,则CASE WHEN
和GROUP BY
可以工作
SELECT
HOSTNAME, MAC ADDRESS, IP_ADDRESS,
CASE
WHEN (SOFTWARE_NAME = 'TeamViewer') THen 'TeamViewer'
ELSE ''
END AS TeamViewer
CASE
WHEN (SOFTWARE_NAME = 'GoogleChrome') THen 'GoogleChrome'
ELSE ''
END AS GoogleChrome
FROM
log_table
GROUP BY
HOSTNAME, MAC ADDRESS, IP_ADDRESS
答案 1 :(得分:0)
使用case
表达式:
SELECT HOSTNAME, MAC_ADDRESS, IP_ADDRESS,
(CASE WHEN SOFTWARE_NAME = 'TeamViewer' THEN SOFTWARE_NAME END) as TeamViewer,
(CASE WHEN SOFTWARE_NAME = 'GoogleChrome' THEN SOFTWARE_NAME END) as GoogleChrome
FROM log_table;
如果您希望每个主机和每个地址一行,请使用聚合:
SELECT HOSTNAME, MAC_ADDRESS, IP_ADDRESS,
MAX(CASE WHEN SOFTWARE_NAME = 'TeamViewer' THEN SOFTWARE_NAME END) as TeamViewer,
MAX(CASE WHEN SOFTWARE_NAME = 'GoogleChrome' THEN SOFTWARE_NAME END) as GoogleChrome
FROM log_table
GROUP BY HOSTNAME, MAC_ADDRESS, IP_ADDRESS;
这不是您指定的输出,但似乎更有用。