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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 [ Resolved ] Union, Each Query w/ own Order By

Author  Topic 

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2006-10-10 : 11:08:04
I am trying to combine 2 queries, each with their own 'order by' and I am having trouble.

This is just an example, not what I'm trying to do, my query is more elaberate but looks simular to this.

SELECT TOP 10 *, 'FieldA' AS SortedBy
FROM TableA
Order By FieldA Desc
UNION ALL
SELECT TOP 10 Precent *, 'FieldB' AS SortedBy
FROM TableA
Order By FieldB Asc


Anyway not to get the following error?
Server: Msg 156, Level 15, State 1, Line 34
Incorrect syntax near the keyword 'UNION'.

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-10-10 : 11:13:19
Try

Select * from
(SELECT TOP 10 *, 'FieldA' AS SortedBy
FROM TableA
Order By FieldA Desc
) T1
UNION ALL
Select * from
(SELECT TOP 10 Precent *, 'FieldB' AS SortedBy
FROM TableA
Order By FieldB Asc
) T2

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2006-10-10 : 11:20:11
Ahh, perfect! Thanks!
Go to Top of Page
   

- Advertisement -