前言
一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理,下面話不多說了,來一起看看詳細的介紹。
create table testtable(
[id] [int] identity(1,1) not null,
[username] [nvarchar](50) null,
[subject] [nvarchar](50) null,
[source] [numeric](18, 0) null
) on [primary]
goinsert into testtable ([username],[subject],[source])
selknmyvxlxect n'張三',n'語文',60 union all
select n'李四',n'數學',70 union all
select n'王五',n'英語',80 union all
select n'王五',n'數學',75 union all
select n'王五',n'語文程式設計客棧',57 uniwww.cppcns.comon all
select n'李四',n'語文',80 union all
select n'張三',n'英語',100
go這裡我用了三種方法來實現行轉列第一種:靜態行轉列
select username 姓名,
sum(case subject when '語文' then source else 0 end) 語文,sum(case subject when '數學' then source else 0 end) 數學,
sum(case subject when '英語' then source else 0 end) 英語 from testtable group by username
用povit行轉列
select * from
(select username,subject,source from testtable) testpivot(sum(source) for subject in(語文,數學,英語)
) pvt
用儲存過程行轉列
alter proc pro_test
@userimages varchar(200),
@subject varchar(20),
@subject1 varchar(200),
@tablename varchar(50)
as declare @sql varchar(max)='select * from (select '+@userimages+' from'+@tablename+') tab
pivot
(sum('+@subject+') for subject('+@subject1+')
) pvt'
exec (@sql)
goexec pro_teknmyvxlxst 'username,subject,source',
'testtable',
'subject',
'語文,數學,英語'
它們的效果都是這樣的
以上三種方式實現行轉列,我們可以根據自己的需求採用不同的方法
總結本文標題: sql語句實現行轉列的3種方法例項
本文位址: /shujuku/shujukuqita/219626.html
sql語句實現行轉列的3種方法
前言 一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理。select n 張三 n 語文 60 union allselect n 李四 n 數學 70 union allselect n 王五 n 英語 ...
sql語句實現行轉列的3種方法例項
一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理,下面話不多說了,來一起看看詳細的介紹。select n 張三 n 語文 60 union all select n 李四 n 數學 70 union all...
SQL語句實現行轉列查詢
表sales 查詢結果如下 1 建表 create table dbo sales id int identity 1,1 not null,year int null,jidu int null,jine int null,primary key clustered id asc with pad...