如何将6列排序为数字顺序

时间:2012-07-02 08:42:12

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

我在6列中获取数据。如何将这些列排序为其值并将它们存储到新列或同一列中。

Input
ID  N1 N2 N3 N4 N5 N6
1   6  4  5  3  1  2
2   42 43 46 45 48 47

Desired Output
ID  N1 N2 N3 N4 N5 N6  S1 S2 S3 S4 S5 S6
1   6  4  5  3  1  2   1  2  3  4  5  6
2   42 43 46 45 48 47  42 43 45 46 47 48 

3 个答案:

答案 0 :(得分:4)

尝试:

DECLARE @t TABLE (ID INT, N1 INT,N2 INT,N3 INT,N4 INT,N5 INT,N6 INT)
INSERT @t VALUES 
(1, 6  ,4  ,5  ,3  ,1  ,2),
(2, 42 ,43 ,46 ,45 ,48 ,47)

DECLARE @t1 TABLE (ID INT, a INT, b VARCHAR(10), RowNum INT)
DECLARE @t2 TABLE (ID INT, a INT, b VARCHAR(10))

INSERT @t1
SELECT  ID, a, b, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY a) RowNum
FROM    @t
UNPIVOT
(
    a FOR b IN ([N1],[N2],[N3],[N4],[N5],[N6])
) unpvt
ORDER BY ID, a

UPDATE  @t1
SET     b = 'S'+ CAST(RowNum AS VARCHAR(10))

INSERT INTO @t2
SELECT  a.ID, a.a, a.b
FROM    @t1 a

SELECT  a.ID, 
        a.N1,a.N2,a.N3,a.N4,a.N5,a.N6, 
        b.S1,b.S2,b.S3,b.S4,b.S5,b.S6
FROM    @t a 
JOIN    (
    SELECT  *
    FROM    @t2
    PIVOT
    (
        MAX(a) FOR b IN ([S1],[S2],[S3],[S4],[S5],[S6])
    ) pvt
) b ON b.ID = a.ID

答案 1 :(得分:2)

不止一种方法给猫皮肤。

Ivan发布的方法到目前为止是执行此操作的首选方式,但如果速度不是问题,那么遵循基于非设置的解决方案会很有趣并且很有趣。

本质上,所有这一切都是相互交换列,直到所有项目都处于正确的位置。

DECLARE @Cnt INTEGER
DECLARE @t TABLE (ID INT, N1 INT,N2 INT,N3 INT,N4 INT,N5 INT,N6 INT)
INSERT @t VALUES 
(1, 6  ,4  ,5  ,3  ,1  ,2),
(2, 42 ,43 ,46 ,45 ,48 ,47)

SET @Cnt = 1
WHILE @Cnt <> 0
BEGIN
  SET @Cnt = 0

  UPDATE @t SET N1 = N2, N2 = N1, @Cnt = @Cnt + 1 WHERE N1 > N2
  UPDATE @t SET N2 = N3, N3 = N2, @Cnt = @Cnt + 1 WHERE N2 > N3
  UPDATE @t SET N3 = N4, N4 = N3, @Cnt = @Cnt + 1 WHERE N3 > N4
  UPDATE @t SET N4 = N5, N5 = N4, @Cnt = @Cnt + 1 WHERE N4 > N5
  UPDATE @t SET N5 = N6, N6 = N5, @Cnt = @Cnt + 1 WHERE N5 > N6
  SELECT * FROM @t

END

答案 2 :(得分:1)

select T.ID, T.N1, T.N2, T.N3, T.N4, T.N5, T.N6, 
       N.X.value('N[1]', 'int') as S1,
       N.X.value('N[2]', 'int') as S2,
       N.X.value('N[3]', 'int') as S3,
       N.X.value('N[4]', 'int') as S4,
       N.X.value('N[5]', 'int') as S5,
       N.X.value('N[6]', 'int') as S6
from YourTable as T
cross apply
  (
    select N
    from (values (N1),(N2),(N3),(N4),(N5),(N6)) as N(N)
    order by N.N
    for xml path(''), type
  ) as N(X)

SE-Data

但使用pivot而不是XML。

select P.ID, P.N1, P.N2, P.N3, P.N4, P.N5, P.N6,
       P.[1] as S1,
       P.[2] as S2,
       P.[3] as S3,
       P.[4] as S4,
       P.[5] as S5,
       P.[6] as S6
from
  (
    select T.ID, T.N1, T.N2, T.N3, T.N4, T.N5, T.N6, N.N, N.rn
    from YourTable as T
    cross apply
      (
        select N,
               row_number() over(order by N.N) as rn
        from (values (N1),(N2),(N3),(N4),(N5),(N6)) as N(N)
      ) N
  ) as T
pivot (min(T.N) for T.rn in ([1],[2],[3],[4],[5],[6])) as P

SE-Data