這是一個典型的 行列轉換問題。這些數據應該有著統一的一列吧,例如:標識人員的身份證號碼之類的。方法別人博客中都很詳盡,我就不在此羅列了。 可檢索關鍵字 「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