您的要求是针对特定数量的原因--3。这使得通过在同一个子查询上执行三向联接,在同一行上获得三个不同的原因成为可能并且易于管理。
首先,让我们将您的错误和原因查询定义为直接的 Access 查询(如果您想要技术的话,可以使用 QueryDef 对象)。
qryErrorCauseInfo
:
select
Error.ID as ErrorID
, Cause.ID as CauseID
from (Error
inner join ErrorCauses
on Error.ID = ErrorCauses.Error)
left outer join Cause
on ErrorCauses.Cause = Cause.ID
顺便说一句,我觉得上面的左连接应该是一个内连接,原因我在评论中提到过。
接下来,让我们进行三向连接,以获取行中可能的原因组合:
qryTotalCause
:
select distinct
*
, iif(Cause1 is null, 0, 1)
+ iif(Cause2 is null, 0, 1)
+ iif(Cause3 is null, 0, 1) as TotalCause
from (
select
eci1.ErrorID
, eci1.CauseID as Cause1
, iif(eci2.CauseID = Cause1, null, eci2.CauseID) as Cause2
, iif(
eci3.CauseID = Cause1 or eci3.CauseID = Cause2
, null
, eci3.CauseID
) as Cause3
from (qryErrorCauseInfo as eci1
left outer join qryErrorCauseInfo as eci2
on eci1.ErrorID = eci2.ErrorID)
left outer join qryErrorCauseInfo as eci3
on eci2.ErrorID = eci3.ErrorID
) as sq
where (
Cause1 < Cause2
and Cause2 < Cause3
) or (
Cause1 < Cause2
and Cause3 is null
) or (
Cause2 is null
and Cause3 is null
) or (
Cause1 is null
and Cause2 is null
and Cause3 is null
)
最后,我们需要一个相关子查询来为每个错误选择原因数量最多的一行(其余行只是相同原因的不同排列):
select
ErrorID
, Cause1
, Cause2
, Cause3
from qryTotalCause as tc1
where tc1.TotalCause = (
select max(tc2.TotalCause)
from qryTotalCause as tc2
where tc1.ErrorID = tc2.ErrorID
)
简单的!(不是 :-)