将行转换为列(可能会旋转)

时间:2018-10-23 15:09:49

标签: sql sql-server

这是我的要求:

create table #TEMP
(
KEY_VALUE VARCHAR(100)
,NAME VARCHAR(100)
,AMOUNT INT
,QUANTITY INT
)

INSERT INTO #TEMP
VALUES
('K1','ABC',100,10000),
('K2','XYZ',200,20000),
('K1','ABC',50,5000),
('K2','XYZ',300,30000),
('K3','MNO',50,500)

select * from #TEMP

enter image description here

由于KEY_VALUE COLUMN匹配2行(K1和K2),因此我想将其转换为以下内容:

KEY_VALUE   NAME    AMOUNT_1 AMOUNT_2   QUANTITY_1 QUANTITY_2
K1          ABC     100      50         10000      5000
K2          XYZ     200      300        20000      30000
K3          MNO     50       NULL       500        NULL

该如何/该怎么做?如果我的问题不清楚,请告诉我。

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()并进行条件聚合:

SELECT KEY_VALUE, NAME,
       MAX(CASE WHEN seq = 1 THEN AMOUNT END) AS AMOUNT_1,
       MAX(CASE WHEN seq = 2 THEN AMOUNT END) AS AMOUNT_2,
       MAX(CASE WHEN seq = 1 THEN QUANTITY END) AS QUANTITY_1,
       MAX(CASE WHEN seq = 2 THEN QUANTITY END) AS QUANTITY_2
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY KEY_VALUE ORDER BY AMOUNT) AS seq
      FROM #TEMP t
     ) t
GROUP BY KEY_VALUE, NAME;

编辑:如果要进行进一步的计算,则可以使用CTE

WITH CTE AS (
     <query>
)
SELECT C.*, 
       C.AMOUNT_1 - C.AMOUNT_1 AS Diff_Amt
FROM CTE C;

答案 1 :(得分:0)

准备数据

CREATE TABLE #t (
    key_value varchar(10),
    name varchar(10),
    amount int,
    quantity int
);

INSERT INTO #t
VALUES 
('K1', 'ABC', 100, 10000),
('K2', 'XYZ', 200, 20000),
('K1', 'ABC', 50, 5000),
('K2', 'XYZ', 300, 30000),
('K3', 'MNO', 50, 500);

查询

WITH t1 (id, key_value, name, amount, quantity)
AS (
    SELECT ROW_NUMBER() OVER (ORDER BY key_value), key_value, name, amount, quantity FROM #t
),
t2
AS (
    SELECT MIN(id) AS min_id, MAX(id) AS max_id, key_value, name 
    FROM t1
    GROUP BY key_value, name
),
t3
AS (
    SELECT t2.key_value, t2.name, 
        t11.amount AS amount_1, t11.quantity AS quantity_1,
        t12.amount AS amount_2, t12.quantity AS quantity_2
    FROM t2 
        INNER JOIN 
        t1 t11 ON t11.key_value = t2.key_value AND t11.name = t2.name 
            AND t11.id = t2.min_id
        LEFT JOIN
        t1 t12 ON t12.key_value = t2.key_value AND t12.name = t2.name 
            AND t12.id = t2.max_id AND t12.id <> t2.min_id
)
SELECT * FROM t3

结果

key_value  name       amount_1    quantity_1  amount_2    quantity_2
---------- ---------- ----------- ----------- ----------- -----------
K1         ABC        100         10000       50          5000
K2         XYZ        300         30000       200         20000
K3         MNO        50          500         NULL        NULL