あなたの要件は、特定の数の原因 (3) に対するものです。これにより、同じサブクエリで 3 方向結合を実行することにより、同じ行で 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
ちなみに、上記の左結合は、コメントで述べた理由から、実際には内部結合であるべきだと思います。
次に、3 方向結合を実行して、考えられる原因の組み合わせを行で取得しましょう。
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
)
最後に、相関サブクエリを使用して、エラーごとに原因の数が最も多い行を 1 つ選択する必要があります (残りの行は、同じ原因の単純な順列です)。
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
)
単純!(いいえ :-)