我理解如何使用左连接返回空行,但这对我不起作用。有没有人对如何返回与连接无关但与where相关的空白行有一些建议。我希望为每个成员拾取最近的行,这适用于所有具有结束日期行的活动成员,但是在他们的TERMDATE<>为空我需要返回一个空行或拾取最近一行。任何和所有的帮助非常感谢。 感谢
SELECT MCSERVICEAUTHORIZATIONS.AUTHNUMBER, CLIENTS.SUBSCRIBERID, MCSERVICEAUTHORIZATIONS.AUTHTYPE, MCSERVICEAUTHORIZATIONS.AUTHSTATUS, GRDSHSCLIENTINSURANCE.LOB, GRDSHSCLIENTINSURANCE.ENROLLMENTDATE, GRDSHSCLIENTINSURANCE.TERMDATE
FROM GRDSHSCLIENTINSURANCE
INNER JOIN CLIENTS
ON GRDSHSCLIENTINSURANCE.PARENTID = CLIENTS.ID
INNER JOIN MCSERVICEAUTHORIZATIONS
ON CLIENTS.ID = MCSERVICEAUTHORIZATIONS.PARENTID
WHERE (MCSERVICEAUTHORIZATIONS.AUTHTYPE = 1234)
AND (GRDSHSCLIENTINSURANCE.TERMDATE IS NULL)
答案 0 :(得分:0)
大多数数据库都支持可以真正帮助进行此类查询的窗口/分析函数。特别是,您可以使用dense_rank()
函数枚举每组GRDSHSCLIENTINSURANCE
条记录的行,因此首先是NULL
终止日期,然后是降序排列的终止日期。你只需要选择第一个:
SELECT sa.AUTHNUMBER, ci.SUBSCRIBERID, sa.AUTHTYPE, sa.AUTHSTATUS,
ci.LOB, ci.ENROLLMENTDATE, ci.TERMDATE
FROM (select ci.*,
dense_rank() over (partition by parentid
order by (case when termdate is null then 0 else 1 end),
termdate desc
) as seqnum
from GRDSHSCLIENTINSURANCE ci
) ci INNER JOIN
CLIENTS c
ON ci.PARENTID = c.ID INNER JOIN
MCSERVICEAUTHORIZATIONS sa
ON c.ID = sa.PARENTID
WHERE sa.AUTHTYPE = 1234 AND
ci.seqnum = 1;
请注意,此查询使用dense_rank()
。这允许返回多行,即使有两行都具有NULL
值。
此外,我添加了表别名以使查询更具可读性。