dizzycat
asked on
SQL using MAX in one table and parameter in another
Hi experts
I have 2 tables 'Session' and 'Count' , I want to retrieve the most recent Count.CountDate for any inputted Session.TrayNumber ie:
Session
Session_ID TrayNumber
1001 3
1002 2
1003 2
1004 2
Count
Session_ID CountDate
1001 30/03/2014
1002 22/03/2014
1003 24/03/2014
1004 26/03/2014
So if I inputted Tray Number = 2 then I get the most recent date for that TrayNumber = 26/03/2014
What I have at the moment will only get the MAX CountDate for all the dates in the CountDate column ie:
SELECT *
FROM Session, Count
WHERE Session.Session_ID = Count.Session_ID
AND Count.CountDate = (SELECT MAX(CountDate)
FROM Count WHERE Session.TrayNumber = @TrayNumber)
Hope that this makes sense and someone can help.
I have 2 tables 'Session' and 'Count' , I want to retrieve the most recent Count.CountDate for any inputted Session.TrayNumber ie:
Session
Session_ID TrayNumber
1001 3
1002 2
1003 2
1004 2
Count
Session_ID CountDate
1001 30/03/2014
1002 22/03/2014
1003 24/03/2014
1004 26/03/2014
So if I inputted Tray Number = 2 then I get the most recent date for that TrayNumber = 26/03/2014
What I have at the moment will only get the MAX CountDate for all the dates in the CountDate column ie:
SELECT *
FROM Session, Count
WHERE Session.Session_ID = Count.Session_ID
AND Count.CountDate = (SELECT MAX(CountDate)
FROM Count WHERE Session.TrayNumber = @TrayNumber)
Hope that this makes sense and someone can help.
ASKER
I'm very sorry but I forgot to mention i'm using the query in a Dataset which dosen't allow the use of Joins.
no reason for the subquery:
select 1001 ID, 3 Tray into #temp
insert into #temp select 1002, 2
insert into #temp select 1003, 2
insert into #temp select 1004, 2
select 1001 Id, cast ('3/30/2014' as smalldatetime) CD into #temp2
insert into #temp2 select 1002, '3/22/2004'
insert into #temp2 select 1003, '3/26/2004'
insert into #temp2 select 1004, '3/30/2004'
-- final query
select max(CD) CD from #temp t
join #temp2 t2 on t.ID = t2.ID
where t.tray = 2 -- change to @trayNumber
group by t.tray
drop table #temp
drop table #temp2
Just a note it IS possible to join on tables in a dataset:
http://msdn.microsoft.com/en-us/library/bb386969(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/bb386969(v=vs.110).aspx
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That's great, thanks.
https://www.experts-exchange.com/Database/Miscellaneous/A_3203-DISTINCT-vs-GROUP-BY-and-why-does-it-not-work-for-my-query.html
in code:
Open in new window