SQL server2005中用pivot实现行列转换
--> --> (Roy)生成测试数据
if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
动态:
declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')
生成静态:
select *
from
Class
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b
生成格式:
/*
Student 数学 物理 英语 语文
------- ----------- ----------- ----------- -----------
李四 77 85 65 65
张三 87 90 82 78
(2 行受影响)
*/
--2000方法:
动态:
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+' from Class group by [Student]')
生成静态:
select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case whe
相关文档:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="fw_student">
<resultMap class="com.sias.Student" id="student">
<result column="name" property="na ......
原始数据
TERMINAL_ID
MAXDATE
TERMINAL_ID
OCCUR_DATE_TIME
TROUBLE_CD
1
12345
20100401102754
12345
20100401102754
210
2
12345
20100401102754
12345
20100401102754
211
3
12345
20100401102754
12345
20100401102754
?09
......
最近在用sqlcmd工具进行数据备份,今天在换到sql2000时突然不能用。原来2000是没有这个工具的:
sql2005:
sqlcmd -S 服务器名或服务器地址 -U 用户 -P 密码 -i "引用的sql语句文件"
sql2000:可以用osql代替,功能一样
osql -S 服务器名或服务器地址 -U 用户 -P 密码 -i "引用的sql语句文件" ......
select
WorksheetID,worker,WorkDate,merchantName ,merchantNo ,manager
, case when insCount>0 then '新装' else '' end InsStr
,case when repCount>0 then '换装' else '' end RepStr
,case when UnInsCount>0 then '撤机' else '' end UnInsStr
,case when FaultCount>0 then '故障处理' els ......