SQL将多行组合到多个列中

时间:2014-12-12 12:19:52

标签: sql sql-server multiple-columns multiple-tables

我一直在看这里和网络上的另一个例子,我无法理解如何做到这一点。

我有一个网站,我将产品的每一条信息都拉到一个表中进行查看,然后加载到csv / excel表中。

它结合了7个表并将它们吐出如下:(切掉表格的其余部分以便于阅读)

ID  Filter     FilterValue  ParentItem  ItemTitle             
---------------------------------------------------------------
7   15         B            LE0001      LB PALETTE WHITE 127MM
7   16         Yes          LE0001      LB PALETTE WHITE 127MM  
7   18         Yes          LE0001      LB PALETTE WHITE 127MM
7   20         Std          LE0001      LB PALETTE WHITE 127MM
7   22         Yes          LE0001      LB PALETTE WHITE 127MM
7   23         Polyester    LE0001      LB PALETTE WHITE 127MM
7   25         White        LE0001      LB PALETTE WHITE 127MM
7   26         127mm        LE0001      LB PALETTE WHITE 127MM

使用此代码(显示的当前列是tblprod.prodID,prodval.valueColumn,prodval.valueKey,tblprod.parentSKU和tblprod.prodTitle)

SELECT 
   tblprod.prodID as ID, prodval.valueColumn as Filter, 
   prodval.valueKey as FilterValue, tblprod.prodSKU as Item, 
   tblprod.parentSKU as ParentItem, tblprod.prodTitle as ItemTitle, 
   tblprod.prodConsumerTitle as ConsumerTitle, tblprod.itemGroup as ItemGroup, 
   tblprod.itemFamily as ItemFamily, tblprod.cutLengthCode as LengthCode, 
   tblprod.prodPackSize as PackSize, tblprod.prodMultQty as MultipleQuantity, 
   tblsu.ImportCode as SalesUnit, tblprod.prodPrice as SalesPrice , 
   tblprod.qtyDependent as QtyDep, tblprod.qtyTarget as Limit, 
   tblprod.targetPrice as Price, tblprod.prodLegacyImage as MainImage,
   catprod.IsPrimary as SafetyinMind, featlists.prodList as NEWLimited      
FROM 
   [Eclipse].[dbo].[tbl_Product] AS tblprod
LEFT JOIN 
   [Database].[dbo].[tbl_SalesUnit] AS tblsu ON tblsu.ID = tblprod.saleUnit
LEFT JOIN 
   [Database].[dbo].[tbl_ProductFilter] AS prodfil ON prodfil.ProdID = tblprod.prodID
LEFT JOIN 
   [Database].[dbo].[tbl_ProductFilterValues] AS prodval ON prodval.valueID = prodfil.valueID
LEFT JOIN
   [Database].[dbo].[tbl_ProductstoFeaturedLists] AS prodlists ON prodlists.prodID = tblprod.prodID
LEFT JOIN
   [Database].[dbo].[tbl_FeaturedLists] AS featlists ON featlists.ID = prodlists.listID
LEFT JOIN 
   [Database].[dbo].[tbl_CategoryProducts] AS catprod ON catprod.prodID = tblprod.prodID

重要的是我想要组合相同ID的行,从Filter列(prodval.valueColumn)创建列标题,并用相应的值(prodval.valueKey)填充它们

我的问题是我只是不知道如何实现这一点而且在阅读其他答案时我迷失了,其次有19个过滤器,而不是每个产品都将拥有所有这些(你可以看到上面的产品有8个)当我这样做时,我不确定这是否会引起任何问题。过滤器的范围从15到33,所有这些都被使用,但仅限于不同的产品。

示例表如下所示。

ID  ParentItem  ItemTitle               Filter 15   Filter 16   Filter 17   Filter 18   Filter 19   Filter 20   Filter...
7   LE0001      LB PALETTE WHITE 127MM  B           YES                     YES                     Std 

如果有人能提供任何帮助我会非常感激,我无法理解它。

抱歉忘记提及我正在使用SQL Server Management Studio

2 个答案:

答案 0 :(得分:1)

尝试以下解决方案:

DECLARE @Columns VARCHAR(max)
;WITH cte
     AS (SELECT Min(Filter) minimum,
                Max(Filter) maximum
         FROM   yourtable)
SELECT @Columns = Stuff((SELECT ',' + '[ ' + CONVERT(VARCHAR(30), number, 121) + ']'
                         FROM   master..spt_values N
                         WHERE  EXISTS (SELECT 1
                                        FROM   cte
                                        WHERE  n.number BETWEEN cte.minimum AND cte.maximum)
                                AND type = 'P'
                         FOR XML PATH('')), 1, 1, '')

DECLARE @sql NVARCHAR(max)= 'select [ID],[ParentItem],[ItemTitle],' + @Columns + 
                            ' from (select [ID],[ParentItem],[ItemTitle],[Filter],[FilterValue] from yourtable) t 
                            pivot
                            (MAx(FilterValue)
                            FOR Filter in(' + @Columns + ')
                            )as pvt'

EXEC sp_executesql
  @sql 

sqlfiddle

答案 1 :(得分:0)

使用PIVOT获得结果。的 Fiddler Demo

CREATE TABLE #Sample
(
    ID INT,  
    Filter INT,    
    FilterValue VARCHAR(100),  
    ParentItem VARCHAR(100),  
    ItemTitle VARCHAR(100)
)

INSERT INTO #Sample VALUES(7,   15,'B',   'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   16,'Yes', 'LE0001','LB PALETTE WHITE 127MM')  
INSERT INTO #Sample VALUES(7,   18,'Yes', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   20,'Std', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   22,'Yes', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   23,'Polyester',    'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   25,'White','LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   26,'127mm','LE0001','LB PALETTE WHITE 127MM')


SELECT P.ID,P.ParentItem, P.ItemTitle, 
 Min(Filter15) Filter15,
 Min(Filter16) Filter16 ,
 Min(Filter17)Filter17,
 Min(Filter18)Filter18,
 Min(Filter19)Filter19,
 Min(Filter20)Filter20,
 Min(Filter21)Filter21,
 Min(Filter22)Filter22,
Min(Filter23)Filter23,
Min(Filter24)Filter24,
Min(Filter25)Filter25,
Min(Filter26)Filter26,
Min(Filter27)Filter27,
Min(Filter28)Filter28,
Min(Filter29)Filter29,
Min(Filter30)Filter30,
Min(Filter31)Filter31,
Min(Filter32)Filter32,
Min(Filter33)Filter33
FROM 
 (SELECT *,
               'Filter' + CONVERT(VARCHAR(30), Filter)  AS Filter_A

        FROM   #Sample
 ) AS A

 PIVOT (Min(A.FilterValue) FOR Filter_A in 
      (Filter15,Filter16,Filter17,Filter18,Filter19,
       Filter20,Filter21,Filter22,Filter23,Filter24,
       Filter25,Filter26,Filter27,Filter28,Filter29,
       Filter30,Filter31,Filter32,Filter33)) AS P
GROUP BY P.ID,P.ParentItem, P.ItemTitle