PIVOT 使您可以为开放架构和其他需要将行旋转为列的方案生成交叉分析报表,并且可能同时计算聚合并且以有用的形式呈现数据。
开放架构方案的一个示例是跟踪可供拍卖的项目的数据库。某些属性与所有拍卖项目有关,例如,项目类型、项目的制造日期以及它的初始价格。只有与所有项目有关的属性被存储在 AuctionItems 表中:
CREATE TABLE AuctionItems
(
itemid INT NOT NULL PRIMARY KEY NONCLUSTERED,
itemtype NVARCHAR(30) NOT NULL,
whenmade INT NOT NULL,
initialprice MONEY NOT NULL,
/* other columns */
)
CREATE UNIQUE CLUSTERED INDEX idx_uc_itemtype_itemid
ON AuctionItems(itemtype, itemid)
INSERT INTO AuctionItems VALUES(1, N''Wine'', 1822, 3000)
INSERT INTO AuctionItems VALUES(2, N''Wine'', 1807, 500)
INSERT INTO AuctionItems VALUES(3, N''Chair'', 1753, 800000)
INSERT INTO AuctionItems VALUES(4, N''Ring'', -501, 1000000)
INSERT INTO AuctionItems VALUES(5, N''Painting'', 1873, 8000000)
INSERT INTO AuctionItems VALUES(6, N''Painting'', 1889, 8000000)
其他属性特定于项目类型,并且不同类型的新项目被不断地添加。这样的属性可以存储在不同的 ItemAttributes 表中,其中每个项属性都存储在不同的行中。每个行都包含项目 ID、属性名称和属性值:
CREATE TABLE ItemAttributes
(
itemid INT NOT NULL REFERENCES AuctionItems,
attribute NVARCHAR(30) NOT NULL,
value SQL_VARIANT NOT NULL,
PRIMARY KEY (itemid, attribute)
)
INSERT INTO ItemAttributes
VALUES(1, N''manufacturer'', CAST(N''ABC'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(1, N''type'', CAST(N''Pinot Noir'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(1, N''color'', CAST(N''Red'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(2, N''manufacturer'', CAST(N''XYZ'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(2, N''type'', CAST(N''Porto'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(2, N''color'', CAST(N''Red'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(3, N''material'', CAST(N''Wood'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(3, N''padding'', CAST(N''Silk'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(4, N''material'', CAST(N''Gold'' AS NVARCHAR(15)))
INSERT INTO ItemAttributes
VALUES(4, N''inscription'', CAST(N''One ring '' AS NVARCHAR(50)))
INSERT INTO ItemAttributes
VALUES(4, N''size'', CAST(10 AS INT))
INSERT INTO ItemAttributes
VALUES(5, N''artist'', CAST(N''Claude Monet'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(5, N''name'', CAST(N''Field of Poppies'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(5, N''type'', CAST(N''Oil'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(5, N''height'', CAST(19.625 AS NUMERIC(9,3)))
INSERT INTO ItemAttributes
VALUES(5, N''width'', CAST(25.625 AS NUMERIC(9,3)))
INSERT INTO ItemAttributes
VALUES(6, N''artist'', CAST(N''Vincent Van Gogh'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(6, N''name'', CAST(N''The Starry Night'' AS NVARCHAR(30)))
INSERT INTO ItemAttributes
VALUES(6, N''type'', CAST(N