How to transform rows to columns

后端 未结 4 395
Happy的楠姐
Happy的楠姐 2020-12-06 02:54

I have a simple problem when querying the SQL Server 2005 database. I have tables called Customer and Products (1->M). One customer has most 2 products. Instead of output as

4条回答
  •  暖寄归人
    2020-12-06 03:28

    As others have mentioned, SQL 2005 has the PIVOT function which is probably the best for general use. In some cases, however, you can simply do something like this.

    Select 
     Customer,
     Sum(Case When Product = 'Foo' Then 1 Else 0 End) Foo_Count,
     Sum(Case When Product = 'Bar' Then 1 Else 0 End) Bar_Count
    From Customers_Products
    Group By Customer
    

提交回复
热议问题