SQL 實現行列轉換

2021-08-25 18:20:57 字數 2068 閱讀 5640

今天有個網友有這樣的需求,那就看看這個例項吧

create table tb(姓名 varchar(10) , 課程 varchar(10) , 分數 int)

insert tb

select '張三','語文',60 union all

select '張三','數學',70 union all

select '張三','英語',80 union all

select '張三','物理',90 union all

select '李四','語文',65 union all

select '李四','數學',75 union all

select '李四','英語',85 union all

select '李四','物理',95

go第一種:

select [姓名]=max([姓名]), 數學=sum(case when [課程]='數學' then [分數] else 0 end),物理=sum(case when [課程]='物理' then [分數] else 0 end),英語=sum(case when [課程]='英語' then [分數] else 0 end),語文=sum(case when [課程]='語文' then [分數] else 0 end) from tb group by [姓名]

第二種:

declare @sql varchar(8000)

set @sql = ''

select @sql = @sql+[課程]+'=sum(case when [課程]='''+[課程]+''' then [分數] else 0 end),' from (select distinct [課程] from tb) a

set @sql = left(@sql,len(@sql) - 1)

set @sql = 'select [姓名]=max([姓名]), '+@sql+' from tb group by [姓名] '

exec (@sql)

create table #table (area varchar(10), date varchar(10), count int)

goinsert into #table (area, date, count)

values ('beijing', '2007-01-01',100000)

insert into #table (area, date, count)

values ('guangzhou', '2007-01-01',200000)

insert into #table (area, date, count)

values ('beijing','2007-02-19',300000)

insert into #table (area, date, count)

values ('guangzhou','2007-02-19',400000)

insert into #table (area, date, count)

values ('beijing','2007-03-21',500000)

insert into #table (area, date, count)

values ('guangzhou','2007-03-21',600000)

go--sql2000

select area,

'2007-01-01'=sum(case date when '2007-01-01' then [count] end),

'2007-02-19'=sum(case date when '2007-02-19' then [count] end),

'2007-03-21'=sum(case date when '2007-03-21' then [count] end)

from #table

group by area

go--sql2005

select * from

#table

pivot(sum([count]) for date in (

[2007-01-01],[2007-02-19],[2007-03-21])) b

SQL實現行列轉換 MySQL

示例資料 tablename為col index 實現行列轉換的統計結果 sql語句 select c2,sum case when c3 正式 then 1else 0end as 正式 sum case when c3 臨時 then 1else 0end as 臨時 from col inde...

實現行列轉換

構建測試表 sql create table table1 id integer,name varchar2 10 create table table2 id integer,role varchar2 10 insert into table1 id,name values 1,張三 inser...

oracle實現行列轉換

ql select from student idname chinese math english 1a 90 70 80 2b 80 70 90 3c 80 90 70 select id,name,chinese 課程,chinese 分數 from student union all sel...