1 [序號]
,'張三'
[姓名]
,85
[語文]
,85
[數學]
,85
[英語]
,85
[歷史]
,85
[地理]
,85
[生物]
,85
[化學]
into
tunion
all
select
2 [序號]
,'李四'
[姓名]
,85
[語文]
,85
[數學]
,85
[英語]
,85
[歷史]
,85
[地理]
,85
[生物]
,85
[化學]
union
all
select
3 [序號]
,'王五'
[姓名]
,85
[語文]
,85
[數學]
,85
[英語]
,85
[歷史]
,85
[地理]
,85
[生物]
,85
[化學]
union
all
select
4 [序號]
,'趙六'
[姓名]
,85
[語文]
,85
[數學]
,85
[英語]
,85
[歷史]
,85
[地理]
,85
[生物]
,85
[化學]
--讀取系統表取列
declare
@sql
varchar
(8000
),@str
varchar
(1000)
set@str
=(select
stuff
((select
',['
+name
+']'
from
sys.
columns
where
object_id
in(select
object_id
from
sys.
tables
where
name
='t'
)and
column_id
>
2 for
xmlpath(''
)),1,1
,''))
set@sql
=';select * into #t1 from t unpivot (value for [科目] in('
+@str
+'))a
declare @str1 varchar(1000),@sql1 varchar(8000)
set@str1=(select stuff((select '',[''+[姓名]+'']'' from (select distinct[姓名] from #t1)a for xml path('''')),1,1,''''))
set @sql1=''select [科目],''+@str1+'' from (select [姓名],[科目],[value] from #t1)b pivot(max([value]) for [姓名] in(''+@str1+''))a''
exec(@sql1)
drop table #t1 '
@sql
exec
(@sql)
drop
tablet
PIVOT函式與UNPIVOT函式的運用
pivot用於將行轉為列,完整語法如下 table source pivot 聚合函式 value column for pivot column in unpivot用於將列轉為行,完整語法如下 完整語法 table source unpivot value column for pivot co...
PIVOT函式與UNPIVOT函式的運用
pivot用於將行轉為列,完整語法如下 table source pivot 聚合函式 value column for pivot column in unpivot用於將列轉為行,完整語法如下 完整語法 table source unpivot value column for pivot co...
PIVOT 和 UNPIVOT例項使用
表的內容 1 select subject 張三 李四 from 2 select subject name,val from pivot 3 as p1 4 pivot max val for name in 張三 李四 as p2 5 order by p2.subject 執行結果 表內容 執...