在同一查询中重用查询值

时间:2013-07-19 15:01:09

标签: sql ms-access

要尽快快速...查询下面。

SELECT PriorityDefID, MilestoneDefID, MilestoneName, ContactName, 
IIF(PriorityDefID = 1, (SELECT BonusDaysFH FROM milestone_def WHERE (( MilestoneDefID = IIF(MilestoneDefID = 5, 5, IIF(MilestoneDefID = 6, 6, IIF(MilestoneDefID = 7, 7))) )) ), 
IIF(PriorityDefID = 2, (SELECT BonusDaysFM FROM milestone_def WHERE (( MilestoneDefID = IIF(MilestoneDefID = 5, 5, IIF(MilestoneDefID = 6, 6, IIF(MilestoneDefID = 7, 7))) )) ),
IIF(PriorityDefID = 3, (SELECT BonusDaysFL FROM milestone_def WHERE (( MilestoneDefID = IIF(MilestoneDefID = 5, 5, IIF(MilestoneDefID = 6, 6, IIF(MilestoneDefID = 7, 7))) )) ) ))) AS BonusDaysAllotted,
StartDate, EndDate
FROM GetPerformance
WHERE (((MilestoneDefID) = 5 Or (MilestoneDefID) = 6 Or (MilestoneDefID) = 7));

我最终试图获取MilestoneDefID的值并在子查询中重用它以确定要返回的BonusDays列。子查询想要返回三行,其结果是传递每个值5,6和7.对于从GetPerformance查询返回的每一行,我希望它从该行获取MilestoneDefID,然后进入子查询并传递该MilestoneDefID返回正确数量的BonusDays。

1 个答案:

答案 0 :(得分:1)

我说在此查询中使用union

select a.PriorityDefID, a.MilestoneDefID, a.MilestoneName, a.ContactName,
    b.BonusDaysFH as BonusDaysAllotted, a.StartDate, a.EndDate
from GetPerformance a, milestone_def b
where ((a.MilestoneDefID=5) or (a.MilestoneDefID=6) or (a.MilestoneDefID=7))
    and b.MilestoneDefID=a.MilestoneDefID
    and a.PriorityDefID=1
union
select a.PriorityDefID, a.MilestoneDefID, a.MilestoneName, a.ContactName,
    b.BonusDaysFM as BonusDaysAllotted, a.StartDate, a.EndDate
from GetPerformance a, milestone_def b
where ((a.MilestoneDefID=5) or (a.MilestoneDefID=6) or (a.MilestoneDefID=7))
    and b.MilestoneDefID=a.MilestoneDefID
    and a.PriorityDefID=2
union
select a.PriorityDefID, a.MilestoneDefID, a.MilestoneName, a.ContactName,
    b.BonusDaysFL as BonusDaysAllotted, a.StartDate, a.EndDate
from GetPerformance a, milestone_def b
where ((a.MilestoneDefID=5) or (a.MilestoneDefID=6) or (a.MilestoneDefID=7))
    and b.MilestoneDefID=a.MilestoneDefID
    and a.PriorityDefID=3

可悲的是,这将产生三个查询,但我相信Iif的缺乏会提高性能。