SQL SERVER 多行轉多列

2021-06-16 16:42:35 字數 1549 閱讀 7637

--★轉換結果如上圖

-建立測試標

create table [成績表](

[編號] [int]identity(1,1) not null,

[姓名] [varchar](50)null,

[語文] [numeric](5, 2)null,

[數學] [numeric](5, 2)null,

[英語] [numeric](5, 2)null

) on [primary]

--插入資料(我的是 sqlserver2008 r2)

insert into 成績表([姓名],[語文],[數學],[英語])

values('道一',80,100,90.8),('老二',48,56,60),('張三',88,78,90),('李四',80,90,95),('王五',67,68,56),('劉六',77,68,80)

-- select * from 成績表

--固定轉換 查詢 (結果如上圖)

declare @sql_1 varchar(8000)

select @sql_1=''

select @sql_1= @sql_1 + 'select [編號],[姓名],['+name+']as ''成績'','''+name+''' as ''課程'' from 成績表 union all '

from syscolumns where id=object_id('成績表')  and charindex(name,'編號,姓名')=0

select @sql_1= @sql_1 + ' select distinctnull,null,null,null from 成績表 ' 

--注意!多一行 selectdistinct null,null,null,null from 成績表

print @sql_1

--execute(@sql_1)

declare @sql_2 varchar(8000)

select @sql_2='select [課程] '

select @sql_2=@sql_2 + ',sum(case when [姓名] = '''+[姓名]+''' then 成績 else 0end) '''+[姓名]+''' '

from 成績表

select @sql_2=@sql_2 + ' from ( '+@sql_1 +')as tb where isnull([編號],'''')<>'''' group by [課程]'

print @sql_2

execute(@sql_2)

--再插入資料

insert into 成績表([姓名],[語文],[數學],[英語])

values('鬼七',67,68,56),('王八',77,68,80)

--再執行動態語句 (結果如下圖),動態查詢隨錶變化

hive多行轉多列

一 需求 需要將多行的資料,按照某個維度轉換為一行。轉換前 轉換後 db price area name 為 東北 的total price actual db qty area name 為 東北 的qty。二 解決方案 1 sql select brand,max case when area ...

行列轉換之 多行轉多列,多列轉多行實踐版

行列轉換之 多行轉多列,多列轉多行實踐版 參考 深入行列轉換 多行轉多列,多行的計算 參考 sql server動態行列轉換 要求 實操演示 1.全表 select from temp2 2.構造row number select row number over partition by a ord...

oracle多行轉單行多列

需求 從a轉成b 需要用到以下函式 wm concat 多行轉成一列 case when then else end regexp substr sql如下 select material code,store id,case when regexp substr wm concat shippin...