意外的SQL结果 - 需要建议

时间:2014-05-09 04:32:19

标签: sql subquery

顶级查询只显示我在加入另一个表以在Crystal Reports中执行某些计算之前所期望的结果。

select 
    DriveID, FromDateTime, accountid, LocationID, StatusID 
from 
    DriveMaster 
where 
    AccountID = '3813' 
order by 
    FromDateTime desc;

结果:

Query Results

第二个查询是我应用几个过滤器的地方(指定accountid, locationid, statusid,并且在特定日期之前发生)。

select 
    dm.driveid, dm.fromdatetime, dm.accountid, dpact.ProcedureProjection,
    dpact.ProceduresPerformed, dpact.ProductProjection, dpact.ProductsCollected,
    dm.locationid
from 
    rpt_drivemaster dm
inner join 
    driveprojectionandcollectedtotals dpact on dm.driveid = dpact.driveid
where 
    dm.statusid = 2
    and dm.accountid = '3813'
    and dm.locationid = '4018'
    and dm.fromdatetime < '20140602'
    and dm.fromdatetime in (select top 3 dm2.fromdatetime 
                            from rpt_drivemaster dm2
                            where dm2.accountid = '3813' 
                              and dm2.statusid = 2 
                            order by dm2.fromdatetime desc);

然而,我得到的唯一结果是:

Query Results 2

根据之前的查询,我期待DriveID的结果为:

 1. 314933
 2. 205250
 3. 184779

有关我在这里缺少什么的建议吗?

1 个答案:

答案 0 :(得分:0)

问题出在您在IN中传递的子查询中 - 它返回了包含DriverID 548002314933205250的三行。第一行有LocationID = 31036因此它不会进入结果集,因为在主查询中存在条件dm.locationid='4018'。您也应该在子查询中传递此条件,以获得所需的结果:

select top 3 dm2.fromdatetime 
from rpt_drivemaster dm2
where dm2.accountid='3813' 
  and dm2.statusid=2
  and dm2.LocationID = '4018' 
order by dm2.fromdatetime desc