将数据分配到两列

时间:2016-06-14 11:04:05

标签: sql-server optimization

我正在尝试找出将列的替代行拆分为两列的最佳优化方法。让我通过一个例子解释这个

我有以下数据

Source

我想要的结果集

Resultset

在上面的例子中,替代行被转移到一个新列。我已经提出了一个解决方案但是如果我有数百万条记录则没有优化。

我的解决方案(未优化)

;WITH RecCtea
AS
(
SELECT *, ROW_NUMBER()  OVER (ORDER BY (select 1)) rowid FROM tabA ta  
)
SELECT a.cola,b.cola FROM (
(SELECT * FROM RecCtea rc WHERE rc.rowid%2 = 0) a JOIN 
 (SELECT * from RecCtea rc2 where rc2.rowid%2 != 0) b
 on a.rowid = b.rowid+1
 )

SQLfiddle 不起作用,所以这里是架构

CREATE TABLE tabA (
cola int 
);


INSERT tabA
(
    cola
)
VALUES
(100),(-100),(200),(-250),(300),(-350),(-400),(NULL)

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT [0] AS col1, [1] AS col2
FROM 
(
  SELECT cola, 
         (ROW_NUMBER() OVER (ORDER BY (select 1)) + 1) / 2 AS rn,
         ROW_NUMBER() OVER (ORDER BY (select 1)) % 2 rowid 
  FROM tabA 
) AS src
PIVOT (
   MAX(cola) FOR rowid IN ([0],[1])) AS pvt

<强>输出:

col1    col2
------+------
-100  | 100
-250  | 200
-350  | 300
NULL  | -400

答案 1 :(得分:2)

你可以使用条件聚合CASE EXPRESSIONROUNDABS来完成,不需要窗口函数/透视:

SELECT MAX(CASE WHEN t.cola < 0 THEN t.cola END) as cola_minus,
       MAX(CASE WHEN t.cola > 0 THEN t.cola END) as cola_plus
FROM (SELECT s.cola,ABS(ROUND(t.cola/100)) as group_number
      FROM TabA s) t
GROUP BY t.group_number

每个小组都会获得一个新值group_number,这是cola/100轮次的绝对结果。然后它将按其分组,并使用条件聚合来旋转它们。

答案 2 :(得分:1)

CTE的另一种方式:

;WITH cte AS (
SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rn,
        cola
FROM tabA
)

SELECT  c2.cola,
        c1.cola
FROM cte c1
LEFT JOIN cte c2
    ON c1.rn = c2.rn-1
WHERE c1.rn%2 = 1 AND c2.rn%2 = 0

输出:

cola    cola
-100    100
-250    200
-350    300
NULL    -400