复杂的LEFT JOIN无法按预期工作

时间:2016-10-19 19:21:34

标签: sql intersystems-cache

DBMS是

以下是我的完整查询:

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

为什么我的完整查询不能获得十行?

1 个答案:

答案 0 :(得分:1)

GROUP BY更改为:

GROUP BY m.Name

您正在按第二个表中的列聚合,因此您只能为所有NULL值获取一行。

大多数数据库会拒绝这种语法,但显然Intersystems Cache允许它。