這使正是你要尋找的。首先,一個小桌子的準備。
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;
這是沒有意義的,你是隱式分組樞軸一些屬性,你分組的屬性是什麼?從你的示例數據和結果我不能告訴 – 2012-02-02 17:55:49
請提供更好的樣本數據和結果,並更好地描述你正在嘗試做什麼 – 2012-02-02 17:59:06
不知道我怎樣才能使它更明顯 - 對於具有相同類別的每組行,類別2和大小值,我想要進行轉換,以便將獨特的oPack值分成3列。 – Perplexed 2012-02-02 18:30:31