SQL2005行列转换的另一方法 PIVOT

本文介绍了一个关于销售数据的数据库表构建过程及数据插入操作,并展示了如何使用Pivot来汇总不同月份的销售金额。

CREATE TABLE salesByMonth
(
year char(4),
month char(3),
amount money,
PRIMARY KEY (year, month)
)

INSERT INTO salesByMonth (year, month, amount)
VALUES('2004','Jan', 789.0000)
INSERT INTO salesByMonth (year, month, amount)
VALUES('2004','Feb', 389.0000)
INSERT INTO salesByMonth (year, month, amount)
VALUES('2004','Mar', 8867.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Apr', 778.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','May', 78.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Jun', 9.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Jul', 987.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Aug', 866.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Sep', 7787.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Oct', 85576.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Nov', 855.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2004','Dec', 5878.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2005','Jan', 7.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2005','Feb', 6868.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2005','Mar', 688.0000)
INSERT INTO  salesByMonth (year, month, amount)
VALUES('2005','Apr', 9897.0000)
SELECT *
-- [Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]
FROM ( SELECT amount, month
FROM salesByMonth ) AS salesByMonth
PIVOT ( SUM(amount) FOR month IN
([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])
) AS ourPivot

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值