我在MSSQL中的表中有以下行
Person | value1 | value2 | value3 | value4
John | 4 | 7 | 1 | 2
我希望这行按照如下所示的值排序。
Person | value2 | value1 | value4 | value3
John | 7 | 4 | 2 | 1
可能是我问了一个愚蠢的问题,我希望根据这些列中的值对列名进行排序。
我知道这可以使用查询
来实现SELECT *
FROM tableName
ORDER BY value2, value1, value4, value3 DESC
但是当我更改任何列值时,我必须更改查询以将结果排序。
请帮忙......
答案 0 :(得分:4)
-- sample data
declare @t table
(
person varchar(50),
value1 int,
value2 int,
value3 int,
value4 int
)
insert into @t select 'John', 4, 7, 1, 2
insert into @t select 'Name1', 14, 7, 1, 16
insert into @t select 'Name2', 24, 8, 1, 2
-- query
select
person, v1 = [1], v2 = [2], v3 = [3], v4 = [4]
from
(
select person, rn = row_number() over(partition by person order by a desc), a
from @t t1
unpivot
(
a for b in (value1, value2, value3, value4)
) t2
) t1
pivot
(
max(a) for rn in ([1], [2], [3], [4])
) t2
答案 1 :(得分:1)
除非我遗漏了某些内容,否则你应该在select语句的末尾添加'order by person,value2,value1,value4,value3'。
答案 2 :(得分:1)
我想你想要:
SELECT Person, Value2, Value1, Value4, Valuer
FROM YourTable
答案 3 :(得分:0)
试试这个:
SELECT * FROM tableName ORDER BY value2, value1, value4, value3 DESC