码迷,mamicode.com
首页 > 数据库 > 详细

Sqlserver中PIVOT行转列透视操作

时间:2017-03-21 18:23:21      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:arch   values   esc   代码   来源   entity   ges   int   建表   

创建表:

IF OBJECT_ID(‘T040_PRODUCT_SALES‘) IS NOT NULL
DROP TABLE T040_PRODUCT_SALES
create table T040_PRODUCT_SALES
(
 ID INT IDENTITY(1,1),
   ProductName VARCHAR(20),
   SaleMonth INT,
   SalesCount INT
)

 插入数据并排序:

INSERT INTO T040_PRODUCT_SALES VALUES
(‘Bicycle‘,1,1),
(‘Shoes‘,2,2),
(‘Clothes‘,3,3),
(‘Books‘,4,4),
(‘Medicine‘,5,5),
(‘Drinks‘,6,6),
(‘Shoes‘,7,7),
(‘Books‘,1,2),
(‘Bicycle‘,1,3),
(‘Medicine‘,1,4),
(‘Clothes‘,1,5),
(‘Mobile Phone‘,1,6),
(‘Books‘,1,7),
(‘Medicine‘,1,8),
(‘Shoes‘,1,9),
(‘Bicycle‘,2,10)
SELECT ProductName,
    SaleMonth,
    SUM(SalesCount) AS SalesCount
FROM T040_PRODUCT_SALES
GROUP BY ProductName,
   SaleMonth
ORDER BY ProductName,
      SaleMonth

 技术分享

 

格式:

/****
SELECT 非透视列,
             [透视列 1] AS ‘列名1‘,
             [透视列 2] AS ‘列名2‘,
             [透视列 3] AS ‘列名3‘
FROM (
        -- 源数据
        SELECT 非透视列,
               透视列值的来源列,
               需要聚合的值
        FROM 表
     )AS 别名
PIVOT
     (
        SUM(需要聚合的值)
        FOR 透视列值的来源列 IN ([透视列 1],[透视列 2],[透视列 3])
     )AS 别名
****/

 行转列的代码:

select ProductName,
    ISNULL([1],0) AS ‘1‘,
    ISNULL([2],0) AS ‘2‘,
    ISNULL([3],0) AS ‘3‘,
    ISNULL([4],0) AS ‘4‘,
    ISNULL([5],0) AS ‘5‘,
    ISNULL([6],0) AS ‘6‘  from (
	select ProductName,
     SaleMonth,
     SalesCount from T040_PRODUCT_SALES)
	 as Sales
	 pivot
	 (
	 SUM(SalesCount)
 FOR SaleMonth IN([1],[2],[3],[4],[5],[6])
	 ) as   PIVOTBL

 结果:

技术分享

 

Sqlserver中PIVOT行转列透视操作

标签:arch   values   esc   代码   来源   entity   ges   int   建表   

原文地址:http://www.cnblogs.com/sunliyuan/p/6595977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!