all groups > sql server (alternate) > november 2005 >
You're in the

sql server (alternate)

group:

problem with Select query


problem with Select query Sandy
11/21/2005 12:00:00 AM
sql server (alternate):
Hi,

I have a table A (ID, time,...)

first I want to select rows with max value of time. Then from these rows I
want the row with max ID value.
i am doing the following but its giving me the error mentioned below

select max(ID) from (select * from A where time in ( select max(time) from
A ) )
ERROR: Incorrect syntax near ')'

Where is the problem in my Query. Is there any other way to do this??

any help is greatly appreciated.

Thanks

Re: problem with Select query CK
11/21/2005 12:00:00 AM
Would this only give the the value of max ID as a result? I think Sandy
wants the complete row which has the max ID value.


[quoted text, click to view]

Re: problem with Select query Jens
11/21/2005 1:53:16 AM
This could be a solution:


Select MAX(ID) FROM SomeTable
Where Time =
(
Select MAX(Time) From SomeTable
)

You were missing the aliases:


select max(ID) from
(
select * from A where time in
(
select max(time) from A
) SubQuery1
) SubQuery2


HTH, Jens Suessmeyer.
Re: problem with Select query --CELKO--
11/21/2005 5:38:35 PM
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.

Also data element names like "id" (of what entity?) and time (a
reserved word in SQL) are pretty useless. I am sure that 'A' is a
meaningful name in your industry ...
Re: problem with Select query Erland Sommarskog
11/21/2005 9:53:20 PM
Sandy (a@a.com) writes:
[quoted text, click to view]

The problem is that the derived tables requires aliases:

select max(ID) from (select * from A where time in ( select max(time)
from A ) AS X ) AS Y

But maybe this query serves you better:

SELECT A.ID, A.time
FROM A
JOIN (SELECT time = MAX(time) FROM A) AS A1 ON A.time = A1.time



--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
AddThis Social Bookmark Button