转换sql视图输出

时间:2014-02-20 20:32:52

标签: sql sql-server-2008

是否可以将1列的sql输出格式化为3列?

例如。我目前的输出是:

Column1
   1
   2
   3
   4
   5
   6
   7
   8
   9

这是我想要输出的方式:

Column1 Column2 Column3
   1       2       3
   4       5       6
   7       8       9

1 个答案:

答案 0 :(得分:1)

您可以使用模数除法和ROW_NUMBER()函数来执行此操作:

;WITH cte AS (SELECT *,ROW_NUMBER() OVER(ORDER BY Column1) RN
              FROM Table1)
     ,cte2 AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY RN%3 ORDER BY Column1) RN2                          
               FROM cte)
SELECT MAX(CASE WHEN RN%3 = 1 THEN column1 END) Col1
      ,MAX(CASE WHEN RN%3 = 2 THEN column1 END) Col2
      ,MAX(CASE WHEN RN%3 = 0 THEN column1 END) Col3
      ,RN2 
FROM cte2
GROUP BY RN2

示例:SQL Fiddle