sql語句實現行轉列的3種方法例項

2021-09-25 04:16:09 字數 1740 閱讀 7096

一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理,下面話不多說了,來一起看看詳細的介紹。

select 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 union 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

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_test 'username,subject,source',

'testtable',

'subject',

'語文,數學,英語'

效果都是這樣:

**:

sql語句實現行轉列的3種方法

前言 一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理。select n 張三 n 語文 60 union allselect n 李四 n 數學 70 union allselect n 王五 n 英語 ...

sql語句實現行轉列的3種方法例項

前言 一般在做資料統計的時候會用到行轉列,假如要統計學生的成績,資料庫裡查詢出來的會是這樣的,但這並不能達到想要的效果,所以要在查詢的時候做一下處理,下面話不多說了,來一起看看詳細的介紹。create table testtable id int identity 1,1 not null,user...

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...