Sql convert data into one row from multiple columns

与世无争的帅哥 提交于 2019-12-25 04:28:20

问题


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;


来源:https://stackoverflow.com/questions/22048102/sql-convert-data-into-one-row-from-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!