高级SQL查询斗争

时间:2013-08-16 14:56:36

标签: sql sql-server join greatest-n-per-group

所以基本上我目前遇到的问题是我无法解决如何在SQL Server中进行高级JOIN查询。

我有以下表格:

  • 事件
  • 后果
  • incident_consequence(加入)
  • 严重性

我的查询需要从数据库中提取每个事件记录,并确定其严重性,这是通过与事件相关的后果(在连接表incident_consequence中)完成的。每个结果记录都有一个与之关联的严重性外键。一旦我得到与事件相关的所有后果,我只需要返回具有最高severity.level整数值的那个。

正如您可能在这里看到的那样,我需要将incident_consequences.incident_id加入到所有关系的incidents.id表中,并从那里将incident_consequence.consequence_id加入到outcome.id然后将严重性加到outcome.severity,等等。

我在这方面遇到了很多麻烦,我希望能够很好地了解SQL的聪明人能够帮助我解决这个问题。

这是我到目前为止所做的:

SELECT DISTINCT dbo.incidents.id, MAX(severities1.[level]) AS severities
FROM dbo.incidents
INNER JOIN dbo.incident_consequence
  ON dbo.incidents.id = dbo.incident_consequence.incident_id
INNER JOIN dbo.consequences
  ON dbo.incident_consequence.consequence_id = dbo.consequences.id
INNER JOIN dbo.severities AS severities1
  ON dbo.consequences.severity = severities1.id
LEFT OUTER JOIN dbo.severities AS severities2
  ON severities1.id = severities2.id AND severities1.[level] < severities2.[level]
WHERE (severities2.id IS NULL)
GROUP BY dbo.incidents.id, severities1.[level]

sql join visual

返回:

result of my join query

我需要的是:

enter image description here

非常感谢我能用这个帮助获得任何帮助!

干杯, 本

2 个答案:

答案 0 :(得分:2)

使用order by severity.level descTOP 1返回最严重的行:

SELECT TOP 1 dbo.incidents.id, severities1.[level] AS severities
FROM dbo.incidents
INNER JOIN dbo.incident_consequence
  ON dbo.incidents.id = dbo.incident_consequence.incident_id
INNER JOIN dbo.consequences
  ON dbo.incident_consequence.consequence_id = dbo.consequences.id
INNER JOIN dbo.severities AS severities1
  ON dbo.consequences.severity = severities1.id
WHERE (severities2.id IS NULL)
ORDER BY severities1.[level] DESC

我删除了不必要的DISTINCT,JOIN,MAX()和GROUP BY。

我留在你的别名中,但它们非常规长 - 你可以通过缩短它们来提高可读性。

答案 1 :(得分:2)

如果我理解正确,我不明白为什么你甚至需要第二次加入严重性。

而是尝试像

这样的东西
SELECT  DISTINCT 
    dbo.incidents.id, 
    MAX(severities1.[level]) AS severities
FROM    dbo.incidents INNER JOIN 
    dbo.incident_consequence ON dbo.incidents.id = dbo.incident_consequence.incident_id INNER JOIN 
    dbo.consequences ON dbo.incident_consequence.consequence_id = dbo.consequences.id INNER JOIN 
    dbo.severities AS severities1 ON dbo.consequences.severity = severities1.id 
GROUP BY dbo.incidents.id