首先,----
如果是一个糟糕的列名,但我想不出更好的办法,所以我保留了它。
您可以在构建查询字符串时在对列进行排序的位置动态构建查询。
declare @SQL nvarchar(max)
set @SQL = '
select [----]'+
(
select ', '+T2.N.value('local-name(.)', 'nvarchar(128)')
from (
select DO, MO, BC, NI, SC
from T
where [----] = 'Total'
for xml path(''), type
) as T1(X)
cross apply T1.X.nodes('*') as T2(N)
order by T2.N.value('.', 'int') desc
for xml path('')
)+'
from T'
exec (@SQL)
SQL小提琴
更新
如果您认为构建动态查询的 XML 版本有点复杂和不直观,您可以使用它来代替,完全没有 XML 的东西。
declare @SQL nvarchar(max)
declare @Col nvarchar(128)
declare C cursor local fast_forward for
select U.Col
from (
select DO, MO, BC, NI, SC
from T
where [----] = 'Total'
) as T
unpivot(Val for Col in (DO, MO, BC, NI, SC)) as U
order by U.Val desc
set @SQL = 'select [----]'
open C
fetch next from C into @Col
while @@FETCH_STATUS = 0
begin
set @SQL = @SQL + ',' + @Col
fetch next from C into @Col
end
close C
deallocate C
set @SQL = @SQL + ' from T'
exec (@SQL)
SQL小提琴