1

是否可以在sql server中从左到右对字段进行排序?例如

----    DO  MO  BC  NI  SC
Total   22  44  53  57  24
Prod A  0   24  0   24   0
Prod B  0   0   0   20   7
Prod C  0   20  0   13  13

会成为:

----    NI  BC  MO  SC  DO
Total   57  53  44  24  22
Prod A  24   24  0   0   0
Prod B  20   7   0   0   0
Prod C  20   13  13  0   0

这将忽略我可以更新的列名。

谢谢

4

1 回答 1

1

虽然我从不推荐使用这种方法(因为这似乎是针对表示逻辑的),但它确实激发了我找到一种方法来完成结果的兴趣。

这是一种同时使用pivot和的方法unpivot。您丢失了列标题(但无论如何在转换后它们不再准确):

WITH CTE AS (
  SELECT field, field2, field3
  FROM 
     (SELECT field, do, mo, bc, ni, sc
      FROM yourresults) p
  UNPIVOT
     (field3 FOR field2 IN 
        (do, mo, bc, ni, sc)
     )AS unpvt
  ),
CTE2 AS (
  SELECT field, 
    field3,
    row_number() over (partition by field order by field3 desc) rn
  from cte
  )
SELECT field, [1], [2], [3], [4], [5]
FROM (
  SELECT field, field3, rn
  FROM CTE2) P
PIVOT 
(
  max(field3)
  FOR rn IN
( [1], [2], [3], [4], [5] )
) AS pvt

SQL 小提琴演示

于 2013-11-08T13:26:52.053 回答