这是一个典型的 行列转换问题。这些数据应该有着统一的一列吧,例如:标识人员的身份证号码之类的。方法别人博客中都很详尽,我就不在此罗列了。 可检索关键字 “SQL 行列转换”或者看下面链接
http://www.cnblogs.com/zhangzt/archive/2010/07/29/1787825.html
http://hi..com/wrgcxfcoybinpur/item/90f388e2ec0f853286d9decc
② SQL 查询 表格的转换,将列转换成行显示
SELECTSN,SUM(CASEWHENField_Name='BL1_Ver'THENField_ValueEND)BL1_Ver,
SUM(CASEWHENField_Name='BL2'THENField_ValueEND)BL2,
SUM(CASEWHENField_Name='BL3'THENField_ValueEND)BL3
FROM表名
GROUPBYSN
③ sql语句列转行
主要应用case语句来解决行转列的问题
行转列问题主要分为两类
1)简单的行转列问题:
示例表:
id
sid
course
result
1
2005001
语文
80.0
2
2005001
数学
90.0
3
2005001
英语
80.0
4
2005002
语文
56.0
5
2005002
数学
69.0
6
2005002
英语
89.0
执行
select
sid,语文=isnull(sum(case
course
when
'语文'
then
result
end),0),
数学=isnull(sum(case
course
when
'数学'
then
result
end),0),
英语=isnull(sum(case
course
when
'英语'
then
result
end),0)
from
result
group
by
sid
order
by
sid
得出结果
sid
语文
数学
英语
2005001
80.0
90.0
80.0
2005002
56.0
69.0
89.0
④ SQL列转行
用case when结构就行了
SELECT * FROM dbo.pvtCustOrders
SELECT custid,years,qty
from dbo.pvtCustOrders
unpivot(qty for years in([2002],[2003],[2004]))as up
GO
⑤ SQL 怎么将列改为行显示
姓名 课程 分数
张三 语文 74
张三 数学 83
张三 物理 93
李四 语文 74
李四 数学 84
李四 物理 94
姓名 语文 数学 物理
李四 74 84 94
张三 74 83 93
select 姓名 as 姓名 ,
max( case 课程 when '语文' then 分数 else 0 end) 语文,
max( case 课程 when '数学' then 分数 else 0 end) 数学,
max( case 课程 when '物理' then 分数 else 0 end) 物理
from tb
group by 姓名
参照写一下
⑥ SQL把查询出的一个列转换成行
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(Name)
from syscolumns where ID=object_id('Class') and Name not in('Student')
order by Colid
exec('select Student,[Course],[Score] from Class unpivot ([Score] for [Course] in('+@s+'))b')
go
select
Student,[Course],[Score]
from
Class
unpivot
([Score] for [Course] in([数学],[物理],[英语],[语文]))b
⑦ SQL语句如何列变行
select 字段名按照你要求的排序就行了
select a,b,c from tableName 那么输出就是 abc对应的顺序
⑧ sql把列变成行
可以用pivot table