I need to do a sort on a T-SQL unioned query. No matter how I write the query, I'm getting a syntax error once I introduce the ORDER BY
clause.
Incorrect syntax near the keyword 'order'
T-SQL query
WITH s1
AS (select '1' as id
union
select '4' as id
union
select '2' as id
union
select '3' as id
union
select '5' as id
),
s2
AS (select '4' as id,
100 as val
union
select '1' as id,
500 as val
union
select '3' as id,
700 as val
union
select '2' as id,
800 as val
)
(select '9' as id,
700 as val) -- id 9 should stay on first row
UNION
(select s1.id,
s2.val
from s1
Left join s2
on s1.id = s2.id --Order by s2.val causing a syntax error )
Query output
id | val |
---|
1 | 500 |
2 | 800 |
3 | 700 |
4 | 100 |
5 | NULL |
9 | 700 |
Desired output
id | val |
---|
9 | 700 |
4 | 100 |
1 | 500 |
3 | 700 |
2 | 800 |
5 | NULL |
3条答案
按热度按时间1szpjjfi1#
Add an additional column specially for ordered, but don't select it e.g.
mftmpeh82#
Your end part should be like this for desired output.
Edit: TOP 100 percent doesn't work in newer versions. (TOP [hard coded value]) will work but it would not be a clean solution).
wmtdaxz33#
The
order by
clause needs to be applied to the finalselect
. You can use a subquery to perform theunion
and then select the results of the subquery and order them. Acase
expression in theorder by
clause will force the'9'
row to the top of the results.dbfiddle .