Question

The top query is just showing the results I am expecting before I join another table to perform some calculations in Crystal Reports.

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

Results:

Query Results

This second query is where I apply a couple of filters (specifying accountid, locationid, statusid, and which occur before a specific date).

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);

The only results I am getting however are:

Query Results 2

Based on the earlier query, I was expecting results for DriveIDs of:

 1. 314933
 2. 205250
 3. 184779

Any suggestions on what I am missing here?

Was it helpful?

Solution

The problem is in your subquery that is passed in the IN – it is returning three rows with DriverID 548002,314933 and 205250. The first row has LocationID = 31036 so it doesn't go in the result set because in your main query there is a condition dm.locationid='4018'.You should pass this condition in the subquery too, to get the desired result :

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top