0

我正在尝试累积 SQL Server 运输系统中事件事件数量的年初至今总数,以便在图表中显示。

我目前拥有的:

SELECT EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM  Event
INNER JOIN
        PortEvent ON Event.PortEventID = PortEvent.ID
INNER JOIN
        EventType ON PortEvent.EventID = Event.ID

WHERE Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name

这会返回什么;

Incident Name       Occurrence

Incident 1              1
Incident 3              4
Incident 4              7

我想要的是:

Incident Name       Occurrence

Incident 1              1
Incident 2              0
Incident 3              4
Incident 4              7
Incident 5              0

有没有办法简单地做到这一点?我看过一些关于 SO 的示例,但仅适用于相邻的表。

谢谢

4

4 回答 4

1

您的EventType ON PortEvent.EventID = Event.ID情况有问题。下面的查询必须解决您的问题。

SELECT ET.Name AS [Incident Name], COUNT(E.ID) AS [Occurrence]
FROM EventType ET
  LEFT JOIN PortEvent PE
    ON ET.ID = PE.EventID
  LEFT JOIN Event E
    ON PE.EventID = E.ID
      AND E.IsIncident = 1
      AND E.Date BETWEEN ([Start of Year] AND Now)
GROUP BY ET.Name

更新

如果您只想包含在结果事件中,您可以尝试以下操作:

    ON PE.EventID = E.ID
      AND E.Date BETWEEN ([Start of Year] AND Now)
   WHERE E.IsIncident = 1
GROUP BY ET.Name
于 2013-10-04T13:10:33.580 回答
0

仅仅使用左连接是不够的。您需要重新排序查询,以便所有事件类型都在最左边的记录集中(这就是我如何可视化它)。此外,您需要去掉 where 子句并将其添加到事件表的连接中,因为如果没有,它也可能是内部连接。

SELECT
    EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM  EventType
LEFT JOIN PortEvent ON Event.PortEventID = PortEvent.ID
LEFT JOIN Event ON PortEvent.EventID = Event.ID and Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name
于 2013-10-04T12:59:57.140 回答
-1

(CASE WHEN COUNT(Event.ID) = 0 THEN 0 ELSE COUNT(Event.ID) END) AS [发生]

于 2013-10-04T13:00:41.173 回答
-1

将 EventType 的 INNER JOIN 更改为 Left Join。这将返回 Event 和零个或多个 EventType

SELECT EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence] 
FROM  Event
LEFT JOIN
        PortEvent ON Event.PortEventID = PortEvent.ID
LEFT JOIN
        EventType ON PortEvent.EventID = Event.ID

WHERE Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name
于 2013-10-04T13:00:52.727 回答