按SQL Server 2008中的出现次数进行透视

时间:2012-02-02 17:46:57

标签: sql sql-server-2008 pivot

我有以下数据:

enter image description here

我想将数据透视为这样。每个Size最多有三个oPack值,我希望Category + Category2 + Size的每个组合的所有oPack值在最后3列中按递增顺序列出。

Category   | Category2 | Size      | Pack1 | Pack2 | Pack3
Chilled...  Chilled     1.75-1.89L  1750    1890    NULL
Chilled...  Chilled     1.75/1.89L  1750    1890    NULL
Chilled...  Chilled     1.75L       1750    NULL    NULL
Chilled...  Chilled     1.89/2.63L  1890    2630    NULL
...
Chilled...  Chilled     400-710mL   400     NULL    NULL

我尝试过类似的事情:

select [Category],[Category2], [Pack1], [Pack2], [Pack3]
from (
  select [Category],[Category2],[size], oPack
  from myTable) p
pivot (Max(oPack) for oPack in ([Pack1], [Pack2], [Pack3])) as pvt

1 个答案:

答案 0 :(得分:3)

这完全符合您的要求。首先,做一点桌子准备。

IF object_id('tempdb.dbo.#Drinks') IS NOT NULL DROP TABLE #Drinks;
GO
CREATE TABLE #Drinks (
   Category1 varchar(40),
   Category2 varchar(40),
   Size varchar(20),
   Pack int
);

INSERT #Drinks VALUES
   ('Chilled Juices & Drinks', 'Chilled', '1.75-1.89L', 1750),
   ('Chilled Juices & Drinks', 'Chilled', '1.75-1.89L', 1890),
   ('Chilled Juices & Drinks', 'Chilled', '1.75/1.89L', 1750),
   ('Chilled Juices & Drinks', 'Chilled', '1.75/1.89L', 1890),
   ('Chilled Juices & Drinks', 'Chilled', '1.75', 1750),
   ('Chilled Juices & Drinks', 'Chilled', '1.89/2.63L', 1890),
   ('Chilled Juices & Drinks', 'Chilled', '1.89/2.63L', 2630),
   ('Chilled Juices & Drinks', 'Chilled', '1.89L', 1890),
   ('Chilled Juices & Drinks', 'Chilled', '1L', 1000),
   ('Chilled Juices & Drinks', 'Chilled', '1L', 1000),
   ('Chilled Juices & Drinks', 'Chilled', '2.63L', 2630),
   ('Chilled Juices & Drinks', 'Chilled', '2.84L', 2840),
   ('Chilled Juices & Drinks', 'Chilled', '250mL', 250),
   ('Chilled Juices & Drinks', 'Chilled', '3.78L', 3780),
   ('Chilled Juices & Drinks', 'Chilled', '355mL', 355),
   ('Chilled Juices & Drinks', 'Chilled', '400-710mL', 400),
   ('Frozen Juices', 'Frozen', '1.60L', 1600),
   ('Frozen Juices', 'Frozen', '1.40L', 1400);

然后,你的解决方案:

WITH Nums AS (
   SELECT
      *,
      'Pack' + Convert(varchar(30), Dense_Rank() OVER (
         PARTITION BY Category1, Category2, Size ORDER BY Pack)
       ) PackNum
   FROM #Drinks
)
SELECT
   *
FROM
   Nums
   PIVOT (Max(Pack) FOR PackNum IN (Pack1, Pack2, Pack3)) P;

而且,一种可能有用的替代解决方案:

SELECT
   *
FROM
   #Drinks
   PIVOT (Max(Pack) FOR Pack IN (
      [250], [355], [400], [1000], [1400], [1600],
      [1750], [1890], [2630], [2840], [3780]
   )) P;