如何将SQL Server行数据转换为列?

时间:2016-02-08 04:49:15

标签: sql-server pivot shape

我查询了这样的数据

member_no cover_version product_id product_name         product_type
--------- ------------- ---------- -------------------- ------------
11421     7                      4 Excellent More       E           
11421     7                     15 Comprehensive Data   D           

但我想像这样塑造这些数据:

member_no cover_version product_e_id product_e_name       product_d_id product_d_name
--------- ------------- ------------ -------------------- ------------ --------------------
11421     7                        4 Excellent More                 15 Comprehensive Data  

我正在使用SQL Server 2008.什么应该是我想要的最佳数据形成方法?

2 个答案:

答案 0 :(得分:2)

假设您只提供了所述的产品类型D和E,那么简单的自我加入将为您提供所需的产品。

如果您想要更通用的内容,请扩展您的问题。

DROP TABLE IF EXISTS #Demo

SELECT
    *
INTO
    #Demo
FROM
    (VALUES 
    (11421, 7, 4, 'Excellent More', 'E')
   ,(11421, 7, 15, 'Comprehensive Data', 'D'))  A
    (member_no, cover_version, product_id, product_name, product_type) 

SELECT
    D.member_no
   ,D.cover_version
   ,E.product_id product_e_id
   ,E.product_name product_e_name
   ,D.product_id product_d_id
   ,D.product_name product_d_name
FROM
    #Demo D
JOIN #Demo E ON D.member_no = E.member_no
                AND D.product_type = 'D'
                AND E.product_type = 'E';


member_no   cover_version product_e_id product_e_name     product_d_id product_d_name
----------- ------------- ------------ ------------------ ------------ ------------------
11421       7             4            Excellent More     15           Comprehensive Data

答案 1 :(得分:1)

如果您想根据未知产品类型动态执行此操作,可以使用此功能。

DECLARE @SQL NVARCHAR(MAX),
        @Columns NVARCHAR(MAX),
        @CaseExpressions NVARCHAR(MAX) = 'MAX(CASE WHEN product_type = ''<<productType>>'' THEN product_id END) AS [product_<<productType>>_id],
                                          MAX(CASE WHEN product_type = ''<<productType>>'' THEN product_name END) AS [product_<<productType>>_name]'

-- build concatenated string with 2 columns for each product_type in your table.
-- group by product_type to get distinct results.
-- replaces <<productType>> with the actual product_type value
SELECT  @Columns = COALESCE(@Columns + ',', '') + REPLACE(@CaseExpressions, '<<productType>>', product_type)
FROM    myTable
GROUP BY product_type

-- build select query
SET     @SQL = 'SELECT  member_no, cover_version,' + @Columns + ' FROM myTable GROUP BY member_no, cover_version'

-- to see what the dynamic sql looks like
PRINT   @SQL 

-- to execute the dynamic sql and see result
EXEC    (@SQL)