2016-12-14 52 views
0

我的数据是按以下格式:SQL Server的复杂数据透视表查询

Customer_ID Order_ID Product_Sub-Category Product Name 
=========== ======== ==================== ============ 
A00001  20001A Vegetables   Onions 
A00001  20001A Vegetables   Garlic 
A00002  20001B Fruits    Apples 
A00002  20001B Fruits    Oranges 
A00002  20001B Vegetables   Spinach 
A00003  20001C Dairy    Milk 
A00003  20001C Dairy    Cheese 
A00004  20001D Meats    Lamb Chops 
A00004  20001D Meats    T-bone Steak 
A00004  20001D Dairy    Yoghurt 
A00004  20001D Fruits    Grapes 
A00004  20001D Vegetables   Garlic 

我需要将其转换成下面的格式。

Customer_ID Order_ID Vegetables  Fruits   Dairy  Meats 
=========== ======== ==========  ======   =====  ===== 
A00001  20001A Onions, Garlic 
A00002  20001B Spinach  Apples, Oranges 
A00003  20001C         Milk, Cheese  
A00004  20001D Garlic   Grapes   Yoghurt  Lamb Chops, T-bone Steak 

请让我知道这是否可以在SQL查询

+0

对不起,格式化搞砸了。 –

+2

是的,它可以做到。是的,这是一个关键。你做了什么尝试? – Santi

+0

繁荣 - https://msdn.microsoft.com/en-us/library/ms177410.aspx,下一个问题? – Anand

回答

0

做假设你想要或需要去动态。

编辑 - 增加了一个SELECT DISTINCT绩效

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Product_Sub-Category]) From YourTable Order by 1 For XML Path('')),1,1,'') 
Select @SQL = ' 
Select [Customer_ID],[Order_ID],' + @SQL + ' 
    From (
     Select A.Customer_ID 
       ,A.Order_ID 
       ,A.[Product_Sub-Category] 
       ,C.String 
     From (Select Distinct Customer_ID,Order_ID,[Product_Sub-Category] From YourTable) A 
     Cross Apply (
         Select String=Stuff((Select Distinct '','' +[Product Name] 
              From YourTable 
              Where Customer_ID = A.Customer_ID 
               and Order_ID = A.Order_ID 
               and [Product_Sub-Category] = A.[Product_Sub-Category] 
              For XML Path ('''')),1,1,'''') 
        ) C 
     ) A 
Pivot (Max(String) For [Product_Sub-Category] in (' + @SQL + ')) p' 
Exec(@SQL); 

返回

enter image description here

如果有帮助,如果你不需要动态的SQL生成如下

Select [Customer_ID],[Order_ID],[Dairy],[Fruits],[Meats],[Vegetables] 
    From (
     Select A.Customer_ID 
       ,A.Order_ID 
       ,A.[Product_Sub-Category] 
       ,C.String 
     From (Select Distinct Customer_ID,Order_ID,[Product_Sub-Category] From YourTable) A 
     Cross Apply (
         Select String=Stuff((Select Distinct ',' +[Product Name] 
               From YourTable 
               Where Customer_ID=A.Customer_ID 
               and Order_ID=A.Order_ID 
               and [Product_Sub-Category]=A.[Product_Sub-Category] 
               For XML Path ('')),1,1,'') 
        ) C 
     ) A 
Pivot (Max(String) For [Product_Sub-Category] in ([Dairy],[Fruits],[Meats],[Vegetables])) p