luckylei66

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
DECLARE @products TABLE(
    City varchar(50),
    Product varchar(50),
    Price decimal
)

DECLARE @productPrice TABLE(
    City varchar(50),
    P1 decimal,
    P2 decimal,
    P3 decimal
)

INSERT INTO @products
SELECT 'Shanghai', 'P1', 50 UNION
SELECT 'Shanghai', 'P2', 100 UNION
SELECT 'Shanghai', 'P3', 150 UNION
SELECT 'Beijing', 'P1', 55 UNION
SELECT 'Beijing', 'P2', 105 UNION
SELECT 'Beijing', 'P3', 155 

SELECT
    T.City, T.P1, T.P2, T.P3
FROM
    @products 
pivot
(
    MAX(price) FOR Product IN ([P1], [P2], [P3])
) AS T


INSERT INTO @productPrice
SELECT
    T.City, T.P1, T.P2, T.P3
FROM
    @products 
pivot
(
    MAX(price) FOR Product IN ([P1], [P2], [P3])
) AS T

SELECT
    unpvt.City,
    unpvt.Product,
    unpvt.Price
FROM
    @productPrice
UNPIVOT
(
    Price FOR Product IN ([P1], [P2], [P3])
) AS unpvt

 

posted on 2013-01-22 11:55  Leo.Wang  阅读(340)  评论(0编辑  收藏  举报