在sql中排序数据行

时间:2012-05-11 14:20:46

标签: sql sorting

请帮助我,我有来自多个表的列,所有这些列的数据类型都是整数

我想对数据行进行排序(不是列(不是排序依据))除主键列

之外

例如

column1(pk)   column2         column3         column4          column5
1             6               5               3                1
2             10              2               3                1
3             1               2               4                3

如何获得此结果

column1(pk)   column2         column3         column4          column5
1             1               3               5                6
2             1               2               3                10
3             1               2               3                4

请快点帮帮我..有可能吗?或者不可能??? 如果不可能,我怎么能得到类似的结果,无论排序

3 个答案:

答案 0 :(得分:1)

您使用的数据库是什么?数据库的功能很重要。其次,这表明存在数据结构问题。需要排序的东西通常是独立的实体。 。 。也就是说,表中的单独行。这篇文章的其余部分回答了这个问题。

如果数据库支持pivot / unpivot,您可以执行以下操作:

(1)取消数据以获取格式, (2)使用row_number()根据值的顺序分配新列。 (3)使用row_number()创建varchar新列名。 (4)使用新列再次旋转数据。

如果此功能不可用,您可以执行类似操作。

首先,将数据更改为行:

(select id, 'col1', col1 as val from t) union all
(select id, 'col2', col2 from t) union all
. . .

打电话给这个。以下查询附加行号:

select br.*, row_number() over (partition by id order by val) as seqnum
from byrow br

将其放入子查询中以进行取消转换。最终的解决方案如下:

with byrow as (<the big union all query>)
select id,
       max(case when seqnum = 1 then val end) as col1,
       max(case when seqnum = 2 then val end) as col2,
       ...
from (select br.*, row_number() over (partition by id order by val) as seqnum
      from byrow br
     ) br
group by id

答案 1 :(得分:0)

您可以使用sql server的pivot功能转换列中的行。在那里应用排序,然后再使用unpivot将列转换为行。

答案 2 :(得分:0)

以下是使用PIVOT的一个很好的例子,您应该能够根据自己的需要进行调整

http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx