如何在sql server中订购中间表数据?

时间:2016-07-08 10:56:49

标签: sql sql-server sql-server-2008 sql-server-2012

我有桌子'测试'数据低于数据

col1    col2
----    -----
448      1
448      1
448      1
449      2
449      2
449      2
450      3

我需要以下格式的数据

col1    col2
----    -----
448      1
449      2
448      1
449      2
448      1
449      2
450      3

2 个答案:

答案 0 :(得分:2)

您想要分发行。您可以通过为每个组(col2)分配行号然后对其进行排序来执行此操作:

select col1, col2
from (select t.*, row_number() over (partition by col2 order by col1) as seqnum
      from t
     ) t
order by seqnum, col1;

答案 1 :(得分:1)

试试这个:

SELECT col1, col2
FROM (
  SELECT col1, col2,
         ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2) AS rn
  FROM mytable) AS t
ORDER BY rn, col1