Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
jp2code
Posting Yak Master
175 Posts |
Posted - 2008-11-11 : 11:48:27
|
How would I write this T-SQL statement correctly?SELECT Name, BadgeFROM EmployeesWHERE Max(ID) I know the script above is wrong; in there WHERE clause, I want to return the greatest ID number. Avoid Sears Home Improvement |
|
tosscrosby
Aged Yak Warrior
676 Posts |
Posted - 2008-11-11 : 12:23:15
|
Try this:SELECT Name, BadgeFROM EmployeesWHERE ID = (select Max(ID) from Employees)Terry |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-11-11 : 12:31:08
|
Assume ID is primary key:SELECT TOP 1 WITH TIESName, BadgeFrom Employeesorder by ID desc |
|
|
readysetstop
Posting Yak Master
123 Posts |
Posted - 2008-11-11 : 12:34:46
|
Another way:SELECT TOP 1 Name, BadgeFROM EmployeesORDER BY ID DESC ____________________________________________________________________________________"Believe in those who are seeking the truth. Doubt those who say they have found it." -Andre Gide |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2008-11-11 : 12:41:23
|
quote: Originally posted by hanbingl Assume ID is primary key:SELECT TOP 1 WITH TIESName, BadgeFrom Employeesorder by ID desc
Does this work in SQL 2000? |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-11-11 : 13:09:34
|
yup, i personally tested quote: Originally posted by sodeep
quote: Originally posted by hanbingl Assume ID is primary key:SELECT TOP 1 WITH TIESName, BadgeFrom Employeesorder by ID desc
Does this work in SQL 2000?
|
|
|
jp2code
Posting Yak Master
175 Posts |
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-11-11 : 13:32:07
|
Say if you have two identical IDs with same Name but different Badges, WITH TIES will show both, without it, only one. If ID is unique, you can go without WITH TIES, if ID can be dups it is save to use WITH TIES ID NAME BADGE----- --------- ---------10 Hanbing Red10 Hanbing Blue9 JP2CODE RedSelect top 1 WITH TIES:ID NAME BADGE----- --------- ---------10 Hanbing Red10 Hanbing Blue |
|
|
|
|
|
|
|