“联合所有”条件下的SQL排序

时间:2013-07-12 07:41:43

标签: sql sql-server database sql-server-2008

我有4个选择表Union All作为这些表的connect0r。

Select [] from [a] inner join [b] on a.[] = b.[]
where []

Union All

Select [] from [a] inner join [b] on a.[] = b.[]
where []

Union All

Select [] from [a] inner join [b] on a.[] = b.[]
where []

Union All

Select [] from [a] inner join [b] on a.[] = b.[]
where []

我已经尝试在最后一行或每个order by [a] asc行中制作select,但它仍然不起作用并成为错误。

2 个答案:

答案 0 :(得分:2)

在第一个select中,您必须拥有别名为A

的列
Select col1 as a [...] from [a] inner join [b] on a.[] = b.[] where []    
Union All   
Select [] from [a] inner join [b] on a.[] = b.[] where []    
Union All    
Select [] from [a] inner join [b] on a.[] = b.[] where []    
Union All    
Select [] from [a] inner join [b] on a.[] = b.[] where []
order by a

答案 1 :(得分:0)

您只需将ORDER BY子句放在语句的末尾,引用首先选择列名/别名。

例如

SELECT a,b customName
FROM T1 
WHERE a = 'yourFilter'
UNION ALL
SELECT foo1,foo2 
FROM T2 
WHERE foo2 IN ('otherFilter','otherFilter2')
ORDER BY customName DESC, a