我正在尝试累积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上看到了一些例子,但仅用于相邻的表格。
由于
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:-1)
(CASE WHEN COUNT(Event.ID)= 0那么0 ELSE COUNT(Event.ID)END)AS [Occurrence]
答案 3 :(得分:-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