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
相关文档:
1. 消除trigger的嵌套调用。最好不要用 EXEC sp_configure 'nested triggers', '0', 应该在trigger中使用判断语句, 例如:if not update (name) return。
2. 使用 not for replication 禁止在复制的时候触发trigger。
3. 创建publisher article的时候, 设置 copy user triggers为 true。
这样保证:trigger不会嵌套调 ......
对于每一个数据库来讲,都需要至少一个事务日志文件。事务日志文件是整个数据库的血液,如果没有事务日志的话,那么将无法进行任何操作。
事务日志有什么东西?
事务日志记录着在相关数据库上的操作,同时还存储数据库恢复(recovery)的相关信息。
事务日志与数据库恢 ......
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 ......