SQL?Server縱表轉橫表的實現示例
更新時間:2023年12月06日 08:35:48 作者:趙潤強
在使用SQL?Server數據庫的過程中我們經常會遇到需要將查詢結果從縱表轉成橫表的問題,本文就來介紹一下SQL?Server縱表轉橫表示例,感興趣的可以了解一下
概述
在使用SQL Server數據庫的過程中我們經常會遇到需要將查詢結果從縱表轉成橫表的問題,下面將用一個簡單的實例說明如何使用動態(tài)查詢語句來解決這一問題。
先創(chuàng)建一個表并插入數據如下(縱表):
create table StudentScores ( StudentName varchar(16), Subject varchar(16), Score smallint ) insert into StudentScores values('張三','語文',85) insert into StudentScores values('張三','數學',90) insert into StudentScores values('張三','英語',86) insert into StudentScores values('李四','語文',92) insert into StudentScores values('李四','數學',87) insert into StudentScores values('李四','英語',90)
此時 select * from StudentScores 直接查詢結果如下:
用需要生成橫表字段名的列數據創(chuàng)建一個臨時表并去重:
select distinct Subject as Sub into #temp from StudentScores
最后使用如下語句轉成橫表:
declare @SQL varchar(max) --定義變量@SQL --拼接查詢語句 set @SQL='select StudentName,' select @SQL=@SQL+'sum(case when Subject='''+Sub+''' then Score else 0 end) as '+Sub+' , ' from #temp select @SQL= LEFT(@SQL, len(@SQL)-1) set @SQL=@SQL+ 'from StudentScores group by StudentName' --執(zhí)行查詢 exec(@SQL)
查詢結果如下:
在SQL Server中有一個內置的函數PIVOT也能夠實現同樣的查詢效果。詳細的使用方法請查看SQL Server行列轉換
到此這篇關于SQL Server縱表轉橫表的實現示例的文章就介紹到這了,更多相關SQL Server縱表轉橫表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
Mysql數據庫性能優(yōu)化三(分表、增量備份、還原)
本文主要介紹了Mysql數據庫性能優(yōu)化(分表、增量備份、還原)的相關知識,需要的朋友可以看下2016-12-12