SQL Server 行列转换示例
SQL Server的行列转换功能非常实用,但是由于其语法不好懂,使很多初学者都不愿意使用它。下面我就用示例的形式,逐一展现Pivot和UnPivot的魅力。如下图
1.从Wide Table of Months 转换到 Narrow Table的示例
select [Year],[Month],[Sales] from
(
select * from MonthsTable
)p
unpivot
(
[Sales] for [Year] in ([2001],[2002],[2003])
)t
order by [Year]
2.从Narrow Table 转换到 Wide Table of Years的示例
select * from
(
select * from NarrowTable
)p
pivot
(
Sum(Sales) for [Month] in ([Jan],[Feb],[Mar])
)t
3.从Wide Table of Months 转换到 Wide Table of Years的示例
with d as
(
select [Year],[Month],[Sales] from
(
select * from MonthsTable
)p
unpivot
(
[Sales] for [Year] in ([2001],[2002],[2003])
)t
)
select * from
(
select * from d
)p
pivot
(
Sum(Sales) for [Month] in ([Jan],[Feb],[Mar])
)t
4.从Wide Table of Years 转换到 Narrow Table的示例
select [Year],[Month],[Sales] from
(
select * from YearTable
)p
unpivot
(
Sales for [Month] in ([Jan],[Feb],[Mar])
)t
5.从Narrow Table 转换到 Wide Table of Month的示例
select * from
(
select * from NarrowTable
)p
pivot
(
Sum(Sales) for [Year] in ([2001],[2002],[2003])
)t
6.从Wide Table of Years 转换到 Wide Table of Month的示例
with d as
(
select [Year],[Month],[Sales] from
(
select * from YearTable
)p
unpivot
(
Sales for [Month] in ([Jan],[Feb],[Mar])
)t
)
select * from
(
select * from d
)p
pivot
(
Sum(Sales) for [Year] in ([2001],[2002],[2003])
)t
如需转载,请注明本文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor
相关文档:
--语 句 功 能
--数据操作
SELECT --从数据库表中检索数据行和列
INSERT --向数据库表添加新数据行
DELETE --从数据库表中删除数据行
UPDATE --更新数据库表中的数据
--数据定义
CREATE TABLE --创建一个数据库表
DROP TABLE --从数据库中删除表
ALTER TABLE --修改数据库表结构
CREATE VIEW --创建一个视图
DRO ......
1.字符串函数 :
datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格
length(expression,variable)指定字符串或变量名称的长度。
substring(expression,start,length) 不多说了,取子串
right(char_expr,int_expr) 返回字符串右边int_expr个字符
concat(str1,str2,...)返回来自于参数连结的字符串。dat ......
刚在看书,提到了sql server的模式匹配运算,接着想到了通配符的转义问题,因为太久没用,Google了搜索了一下才想起来,写几句话记录下。 关于通配符的转义,sql server里边提供了关键字escape来处理。但是escape本身不是什么转义符(刚才我就是在这里搞错了),而是将escape后面的符号定义为转义符。举个例: select ......
Introduction to the SQL Server 2008 Resource Governor
Database Administration, Performance Tuning | January 4, 2010 | 4:05 pm
This is an excerpt from my free eBook, Brad’s Sure Guide to SQL Server 2008.
I think most of us are familiar with this situation: a SQL Server database is the bac ......
选择自 CSDN
SQL语句导入导出大全
/******* 导出到excel
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:\temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel
SELECT *
from OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:\tes ......