我有一个名为Events的表,其中有一些已归档,其中有“status”和“type”。我希望根据事件类型,在每个主机的表中使用表Hosts显示当前每个事件的状态。
所以,例如,如果我有这种情况(主机列表和有多少事件,类型不同,有):
Host: Achille. Types: 1 'OS', 1 'File Integrity', 1 'Running Services'
Host: Aiace. Types: 1 'Running Services'
Host: Ulisse. Types: 1 'File integrity'
使用此查询:
SELECT distinct h.name,
(case when e.type = 'File Integrity' then e.status end) as FI,
(case when e.type = 'Running Services' then e.status end) as RS,
(case when e.type = 'Services' then e.status end) as S,
(case when e.type = 'OS' then e.status end) as OS
FROM hosts h
JOIN events e ON h.id = e.host_id
WHERE DATE(e.date) = CURDATE()
GROUP BY h.name;
我得到了这个结果:
其中,对于Achille,仅显示OS事件的状态;为什么? 我补充一点,插入事件时,第一个添加了类型='OS'的事件。
答案 0 :(得分:2)
问题是你没有聚合状态
SELECT h.name,
MAX( case when e.type = 'File Integrity' then e.status end ) as FI,
MAX( case when e.type = 'Running Services' then e.status end ) as RS,
MAX( case when e.type = 'Services' then e.status end ) as S,
MAX( case when e.type = 'OS' then e.status end ) as OS
FROM hosts h
JOIN events e ON h.id = e.host_id
WHERE DATE(e.date) = CURDATE()
GROUP BY h.name;