2016-12-05 30 views
0

如果我有一个如下所示的表。在具有独特性的sql server 2012中的支点

declare @mytble table 
(
orders int, 
product varchar (50), 
quantity int 

) 

INSERT @mytble 

SELECT 100,'CUP','1' UNION ALL 
SELECT 100, 'PLATE',2 UNION ALL 
SELECT 101,'CUP','1' UNION ALL 
SELECT 102,'CUP','2' UNION ALL 
SELECT 103, 'CUP',1 UNION ALL 
SELECT 103,'PLATE','3' UNION ALL 
SELECT 103,'GLASS','1' 

SELECT * FROM @mytble 

将有可能得到这样的输出。

enter image description here

任何建议,请。

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload - 问的问题/ 285557#285557 –

+0

是的,这是可能的。但如何去做取决于你有多少种不同的产品...... – DVT

回答

0

一些动态SQL和DENSE_RANK()函数

Declare @SQL varchar(max) 
Select @SQL = Stuff((Select Distinct ',' + QuoteName(concat('Product',Dense_Rank() over (Order By Product))) 
            + ',' + QuoteName(concat('Quantity',Dense_Rank() over (Order By Product))) 
         From myTable For XML Path('')),1,1,'') 

Select @SQL = 'Select Orders,' + @SQL + ' 
       From (
         Select Orders,Item=concat(''Product'',Dense_Rank() over (Order By Product)),Val=cast(Product as varchar(max)) From myTable 
         Union All 
         Select Orders,Item=concat(''Quantity'',Dense_Rank() over (Order By Product)),Val=cast(Quantity as varchar(max)) From myTable 
        ) A 
       Pivot (max(Val) For Item in (' + @SQL + ')) p' 

Exec(@SQL); 

返回

Orders Product1 Quantity1 Product2 Quantity2 Product3 Quantity3 
100  CUP   1   NULL  NULL  PLATE  2 
101  CUP   1   NULL  NULL  NULL  NULL 
102  CUP   2   NULL  NULL  NULL  NULL 
103  CUP   1   GLASS  1   PLATE  3