SQL如何将表从行转换为列

时间:2016-06-03 07:15:06

标签: sql sql-server sql-server-2008

我想从行到列编写sql查询转置表,如下图所示 enter image description here

非常感谢。

5 个答案:

答案 0 :(得分:2)

我没有使用列的确切名称,但你可以试试这个,

SELECT GOOD2,
       NAME,
       MAX(CASE WHEN [TYPE] = 'BF' THEN VALUE END) BQTY,
       MAX(CASE WHEN [TYPE] = 'RC' THEN VALUE END) BQTY,
       MAX(CASE WHEN [TYPE] = 'ISU' THEN VALUE END) BQTY,
       MAX(CASE WHEN [TYPE] = 'CF' THEN VALUE END) BQTY
FROM   TABLE1
GROUP BY
       GOOD2,
       NAME

答案 1 :(得分:2)

使用透视:

SELECT  Goods_ID, 
        Name, UM, 
        ISNULL([B/F],0) as [B/F], 
        ISNULL([REC],0) as [REC],
        ISNULL([ISU],0) as [ISU],
        ISNULL([C/F],0) as [C/F]
FROM (
    SELECT Goods_ID, Name, UM, [Type], NULLIF([In-Qty],0) as Qty
    FROM YourTable 
    UNION ALL
    SELECT Goods_ID, Name, UM, [Type],NULLIF([Out-Qty],0)
    FROM YourTable 
    UNION ALL
    SELECT Goods_ID, Name, UM, [Type],NULLIF([B-Qty],0)
    FROM YourTable 
    ) as p
PIVOT (
MIN(Qty) FOR [Type] IN ([B/F],[REC],[ISU],[C/F])
) as pvt

输出:

Goods_ID    Name    UM  B/F     REC     ISU     C/F
CH006       CH006   Kg  11648   11648   0       23296
CH007       CH007   Kg  97584   278400  -315006 60978

答案 2 :(得分:0)

你只想按他们分组。这是一个理论上的例子:

SELECT * FROM table_name GROUP BY column_name 

(您需要按照您想要的顺序包含表格中的所有列)

答案 3 :(得分:0)

未经测试,但应该是这样的......

select goods_id, name, [B/F], REC, ISU, [C/F] from 
    (select goods_id, name, UM, B-Qty from 
    yourtable ) 
    tbl pivot (sum(B-Qty) for UM in ( [B/F], REC, ISU, [C/F] ) 
    as p

答案 4 :(得分:0)

我想说你需要使用PIVOT

查看具有不同要求的相同 question ,以及实现预期输出的几乎所有方法。