Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting a Last-type value from a union query 1

Status
Not open for further replies.

cascot

Programmer
Jan 30, 2002
127
CA
If I have SQL something like the following

(
SELECT Something.SomethingId, [Surname] + ', ' + [FirstName] AS MyPerson
FROM Blah Blah Blah
WHERE (((Table.SomeId)=1234))

UNION

SELECT Something_1.SomethingId, [Surname] + ', ' + [FirstName] AS MyPerson
FROM Blah Blah Blah
WHERE (((Table.SomeId)=1234))
)
ORDER BY SomethingId

Let's say it returns 2 records as it stands...

SomethingId MyPerson
1 John Smith
99 Able Andy

Is there somthing else I can add to the SQL so it will return only one record with the name of MyPerson related to the Maximum SomethingId?
 
One way is to insert the data from the two seperate queries into a temporary table and then select just the top 1 from the temporary table

Andy

create table ##tempdata (....)

insert into ##tempdata
....

insert into ##tempdata
....

select top 1 from ##tempdata
order by SomethingId


drop table ##tempdata
 
AWithers,

Thanks for your reply.

That would certainly be a solution, but unfortunately I need a solution that can form part of a much larger and more complex select query. It may not be possible to do it at all.
 
Or use this query as a derived table and wrap it in the SELECT TOP 1. Kind of like this:

Code:
SELECT TOP 1 x.SomethingID, x.MyPerson
FROM (
  SELECT Something.SomethingId, [Surname] + ', ' +
    [FirstName] AS MyPerson
  FROM Blah Blah Blah WHERE (((Table.SomeId)=1234))
 UNION
  SELECT Something_1.SomethingId, [Surname] + ', ' +
    [FirstName] AS MyPerson
  FROM Blah Blah Blah WHERE (((Table.SomeId)=1234))
 ORDER BY SomethingId
 ) AS x
--Angel
-----------------------------------
Every time I lose my mind, I wonder
if it's really worth finding.
 
AngelWPB,

Thanks for your reply, it helped me get the solution with just a little tweak

Having the ORDER BY where it is caused an error, I also wanted the value against the record with the highest SomethingId so I ended up with this

SELECT TOP 1 x.SomethingID, x.MyPerson
FROM (
SELECT Something.SomethingId, [Surname] + ', ' +
[FirstName] AS MyPerson
FROM Blah Blah Blah WHERE (((Table.SomeId)=1234))
UNION
SELECT Something_1.SomethingId, [Surname] + ', ' +
[FirstName] AS MyPerson
FROM Blah Blah Blah WHERE (((Table.SomeId)=1234))
) AS x
ORDER BY SomethingId DESC

Thanks again for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top