复杂的 LEFT JOIN 未按预期工作
Complex LEFT JOIN not working as expected
DBMS 是 intersystems-cache!
这是我的完整查询:
SELECT m.Name AS MessageType, COUNT(l.name) AS MessageCount, CAST(AVG(ResponseTime) AS DECIMAL(5, 2)) AS AvgResponseTime
FROM
(SELECT DISTINCT(name) FROM ENSLIB_HL7.Message) m LEFT JOIN
(
SELECT CAST(li.SessionId AS Bigint) AS session_id, li.name, MIN(li.TimeCreated) AS SessionStart, MAX(lo.TimeCreated) AS SessionEnd, CAST(DATEDIFF(s, MIN(li.TimeCreated), MAX(lo.TimeCreated)) AS DECIMAL(5, 2)) AS ResponseTime
FROM (SELECT h1.SessionId, h1.TimeCreated, $PIECE(RawContent, '|', 4), m1.name FROM ens.messageheader h1, ENSLIB_HL7.Message m1 WHERE h1.MessageBodyId = m1.id AND h1.TimeCreated > DATEADD(mi, -30, GETUTCDATE())) li
JOIN (SELECT h2.SessionId, h2.TimeCreated FROM ens.messageheader h2, ENSLIB_HL7.Message m2 WHERE h2.MessageBodyId = m2.id AND h2.TimeCreated > DATEADD(mi, -30, GETUTCDATE())) lo
ON li.SessionId = lo.SessionId
GROUP BY li.SessionId
) l on m.name = l.name
GROUP BY l.Name
这给了我 4 个结果:
VXU_V04 0 (null)
ADT_A03 3 0.01
ADT_A04 3 0.01
ADT_A08 143 0.01
鉴于有一个结果有 0 条记录,看起来它正在工作。但是,如果我 运行 SELECT DISTINCT(name) FROM ENSLIB_HL7.Message
我得到 10 个结果:
VXU_V04
ADT_A08
ACK_A08
ADT_A03
ACK_A03
ADT_A04
ACK_A04
ACK_V04
ADT_A01
ACK_A01
为什么我的完整查询没有得到十行?
将 GROUP BY
更改为:
GROUP BY m.Name
您正在按 秒 table 中的列进行聚合,因此所有 NULL
值只得到一行。
大多数数据库会拒绝这种语法,但显然 Intersystems Cache 允许它。
DBMS 是 intersystems-cache!
这是我的完整查询:
SELECT m.Name AS MessageType, COUNT(l.name) AS MessageCount, CAST(AVG(ResponseTime) AS DECIMAL(5, 2)) AS AvgResponseTime
FROM
(SELECT DISTINCT(name) FROM ENSLIB_HL7.Message) m LEFT JOIN
(
SELECT CAST(li.SessionId AS Bigint) AS session_id, li.name, MIN(li.TimeCreated) AS SessionStart, MAX(lo.TimeCreated) AS SessionEnd, CAST(DATEDIFF(s, MIN(li.TimeCreated), MAX(lo.TimeCreated)) AS DECIMAL(5, 2)) AS ResponseTime
FROM (SELECT h1.SessionId, h1.TimeCreated, $PIECE(RawContent, '|', 4), m1.name FROM ens.messageheader h1, ENSLIB_HL7.Message m1 WHERE h1.MessageBodyId = m1.id AND h1.TimeCreated > DATEADD(mi, -30, GETUTCDATE())) li
JOIN (SELECT h2.SessionId, h2.TimeCreated FROM ens.messageheader h2, ENSLIB_HL7.Message m2 WHERE h2.MessageBodyId = m2.id AND h2.TimeCreated > DATEADD(mi, -30, GETUTCDATE())) lo
ON li.SessionId = lo.SessionId
GROUP BY li.SessionId
) l on m.name = l.name
GROUP BY l.Name
这给了我 4 个结果:
VXU_V04 0 (null) ADT_A03 3 0.01 ADT_A04 3 0.01 ADT_A08 143 0.01
鉴于有一个结果有 0 条记录,看起来它正在工作。但是,如果我 运行 SELECT DISTINCT(name) FROM ENSLIB_HL7.Message
我得到 10 个结果:
VXU_V04 ADT_A08 ACK_A08 ADT_A03 ACK_A03 ADT_A04 ACK_A04 ACK_V04 ADT_A01 ACK_A01
为什么我的完整查询没有得到十行?
将 GROUP BY
更改为:
GROUP BY m.Name
您正在按 秒 table 中的列进行聚合,因此所有 NULL
值只得到一行。
大多数数据库会拒绝这种语法,但显然 Intersystems Cache 允许它。