Sql convert data into one row from multiple column

2019-08-30 18:53发布

问题:

I have a table

and I want to convert it into one row for each customer number something like this:

Can someone point me to the right place , example where I can do similar thing.

回答1:

You need to use PIVOT. Something like the following query should help.

SELECT CustomerNumber, 
    CASE WHEN [1] > 0 THEN 'Y' ELSE 'N' END [Sony],
    CASE WHEN [2] > 0 THEN 'Y' ELSE 'N' END [LG],
    CASE WHEN [3] > 0 THEN 'Y' ELSE 'N' END [Samsung]
FROM
(SELECT Product1, CustomerNumber
    FROM Table) AS SourceTable
PIVOT
(
    COUNT(Product1)
    FOR Product1 IN ([1], [2], [3])
) AS PivotTable;