Hi:
I have three tables:
Core_Table holds DeviceNo and location codes. The PK is DeviceNo.
DeviceNo Location Code DeviceType
12345 A 2
45678 B 3
DeviceRef_Table holds Device names. The PK is DeviceNo.
DeviceNo DeviceType Device Name
12345 2 A250
45678 3 B456
Test_Table holds Device tests. The PK is TestID. There can be multiple records with the same Device number with differenet test dates.
TestID DeviceNo TestDate
1 12345 01/05/2011
2 45678 05/09/2010
3 12345 11/27/2013
I need to find all Devices that have not been tested in the last 270 days that have a location code of either A or B.
Select Core_Table.DeviceNo,Core_Table.[Location Code] ,
Core_Table.DeviceType, DeviceRef_Table.MtrName,
(Select Test_Table.TestDate whereDATEDIFF(day,Max(Test_Table.TestDate),getdate())>= 270 Or Test_Table.TestDateIsnull) as TestDate
From Core_Table
Join DeviceRef_Tableon Core_Table.DeviceType= DeviceRef_Table.DeviceType
LeftJoin Test_Table on Core_Table.DeviceNo= Test_Table.DeviceNo
Where(Core_Table.[Location Code]='A' or Core_Table.[Location Code] ='B')
GroupBy TestDate,Core_Table.DeviceNo, Core_Table.[Location Code], Core_Table.[Location Number], Core_Table.DeviceType, DeviceRef_Table.MtrName
OrderBy Test_Table.TestDate
This returns Device 12345 with the 01/05/2011 date. It should not even return that Device since it has been tested in the last 270 days. This query seems to work provided there is only one record for a given Device in the Test_Table.
Select Core_Table.DeviceNo, Test_Table.TestDate, Core_Table.[Location Code], Core_Table.DeviceType, DeviceRef_Table.MtrName
From Core_Table
Join DeviceRef_Tableon Core_Table.DeviceType= DeviceRef_Table.DeviceType
LeftJoin Test_Table on Core_Table.DeviceNo= Test_Table.DeviceNo
Where(Core_Table.[Location Code]='A' or Core_Table.[Location Code] ='B')
and(DATEDIFF(day,Max(Test_Table.TestDate),getdate())>= 270 Or Test_Table.TestDateIsnull)
OrderBy test_Table.TestDate
This produces the error:An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
This will probably solve the aggregate problem but will never work. Where TestDate = (DATEDIFF(day,Max(Test_Table.TestDate),getdate())>= 270 Or Test_Table.TestDateIsnull)
I have thought of creating a view that contains all of the max dates from the test table and then querying the view for Devices that have a date difference less than 270 days. I would prfer to use just one query.Any help would be appreciated.
Thanks.
Scott Haldi