一次取两行数据并将数据分成两列?

时间:2015-04-01 20:17:44

标签: sql sql-server tsql

在此示例中,哪些SQL代码会将输入表转换为输出表? (假设有一些排序,奇数行转到column2,偶数行转到column3,在同一输出行上连续奇偶对。)

input table:
column1
  A
  B
  C
  D
  E
  F

output table:
column2    column3
  A          B
  C          D
  E          F

更新 假设有一些排序,奇数行转到column2,偶数行转到column3,在同一输出行上连续奇偶对

2 个答案:

答案 0 :(得分:4)

试试这个:

;WITH CTE AS (
  SELECT ROW_NUMBER() OVER (ORDER BY column1) AS rn, column1
  FROM #mytable
), CTE2 AS (
   SELECT *
   FROM CTE 
   WHERE rn % 2 <> 0
), CTE3 AS (
   SELECT *
   FROM CTE 
   WHERE rn % 2 = 0
)
SELECT c2.column1 AS column2, c3.column1 AS column3
FROM CTE2 AS c2
LEFT JOIN CTE3 AS c3 ON c2.rn = c3.rn - 1 

CTE2包含所有奇数行,而CTE3包含所有偶数行。我们通过c2.rn = c3.rn - 1将连续的奇数 - 偶数对连接起来以获得所需的结果集。

SQL Fiddle Demo

答案 1 :(得分:1)

此方法可轻松更改输出列数

WITH cte AS (
  SELECT
    column1
   ,output_row = (ROW_NUMBER() OVER(ORDER BY column1)-1) / 2 
   ,output_col = (ROW_NUMBER() OVER(ORDER BY column1)-1) % 2
  FROM input_table
)
SELECT
  column2 = [0]
 ,column3 = [1]
FROM cte
PIVOT(MAX(column1) FOR output_col IN ([0],[1])) p