Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've got this table (without a primary key), I know this query isn't correct, but what's its correct equivalent ?
SQL
SELECT siloid, amount, max(tdate)
FROM siolstate
GROUP BY siloid


I want to get all the rows in "siolstate" table which has the latest dates for each silo, I mean Grouped only by of field "siloid"

I thought about something like:
SQL
SELECT *
FROM siolstate
WHERE tdate = (SELECT siloid, max(tdate) FROM siolstate GROUP BY siloid)


but it won't work cause the subquery has two fields

and I thought about this too:
SQL
SELECT *
FROM siolstate
WHERE max(tdate)


but you know ... you can't use aggregation inside WHERE clause.

so ... any ideas?
Posted
Updated 10-Jun-10 12:39pm
v2

I think this is what your are looking for.


SELECT Temp.siloid, temp.tdate,MAIN.amount
FROM
( 
	select siloid, MAX(tdate) AS tdate
	from dbo.siolstate
	group by siloid
) Temp
INNER JOIN dbo.siolstate MAIN ON MAIN.siloid = Temp.siloid AND MAIN.tdate = Temp.tdate
 
Share this answer
 
Comments
Speed.Of.Light 11-Jun-10 16:19pm    
Thanks Prakash!
That's what I was looking for.
How about this approach

SQL
SELECT *
FROM siolstate
WHERE tdate = (SELECT  max(tdate) FROM siolstate as a where siolstate.siloid = a.siloid)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900