从union语句中删除默认顺序

时间:2012-08-24 13:17:57

标签: sql sql-server sql-server-2008 sql-order-by

我想显示如下数据:

Column1        Column2
-----------------------
TotalAvg         60%

A1               50%

B1               70%

Z1               60%

我的sql脚本类似于:

select 'Total Avg' as Column1,'60%' as Column2

union

select Column1,Column2 from tblAvg

我得到的结果是这样的:

Column1        Column2
------------------------

A1               50%

B1               70%

TotalAvg         60%

Z1               60%

问题:我想删除默认排序,并希望按照我们正在进行联合表的顺序得到结果。

4 个答案:

答案 0 :(得分:8)

您可以添加指定结果顺序的列:

select 'Total Avg' as Column1,'60%' as Column2, 1 as OrderCol
union
select Column1,Column2, 2 from tblAvg
order by OrderCol

如果没有order by,数据库可以按任意顺序自由返回行。

答案 1 :(得分:1)

SELECT
  *
FROM
(
  select 0 as pos, 'Total Avg' as Column1, '60%' as Column2
  union
  select 1 as pos,                Column1,          Column2 from tblAvg 
)
  AS data
ORDER BY
  pos, column1, column2

答案 2 :(得分:1)

你可以做这样的事情

select * From
(
select 'Total Avg' as Column1,'60%' as Column2, 1 as ItemOrder

union

select Column1,Column2,2 from tblAvg
) innertable
Order By ItemOrder

答案 3 :(得分:0)

尝试使用

select 'Total Avg' as Column1,'60%' as Column2

union all

select Column1,Column2 from tblAvg