欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SQL?Server縱表轉(zhuǎn)橫表的實現(xiàn)示例

 更新時間:2023年12月06日 08:35:48   作者:趙潤強(qiáng)  
在使用SQL?Server數(shù)據(jù)庫的過程中我們經(jīng)常會遇到需要將查詢結(jié)果從縱表轉(zhuǎn)成橫表的問題,本文就來介紹一下SQL?Server縱表轉(zhuǎn)橫表示例,感興趣的可以了解一下

概述

在使用SQL Server數(shù)據(jù)庫的過程中我們經(jīng)常會遇到需要將查詢結(jié)果從縱表轉(zhuǎn)成橫表的問題,下面將用一個簡單的實例說明如何使用動態(tài)查詢語句來解決這一問題。

先創(chuàng)建一個表并插入數(shù)據(jù)如下(縱表):

create table StudentScores 
(
StudentName varchar(16),
Subject varchar(16),
Score  smallint
)

insert into StudentScores
values('張三','語文',85)
insert into StudentScores
values('張三','數(shù)學(xué)',90)
insert into StudentScores
values('張三','英語',86)
insert into StudentScores
values('李四','語文',92)
insert into StudentScores
values('李四','數(shù)學(xué)',87)
insert into StudentScores
values('李四','英語',90)

此時 select * from StudentScores 直接查詢結(jié)果如下:

用需要生成橫表字段名的列數(shù)據(jù)創(chuàng)建一個臨時表并去重:

select distinct Subject as Sub into #temp from StudentScores

最后使用如下語句轉(zhuǎn)成橫表:

 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)

查詢結(jié)果如下:

在SQL Server中有一個內(nèi)置的函數(shù)PIVOT也能夠?qū)崿F(xiàn)同樣的查詢效果。詳細(xì)的使用方法請查看SQL Server行列轉(zhuǎn)換

到此這篇關(guān)于SQL Server縱表轉(zhuǎn)橫表的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)SQL Server縱表轉(zhuǎn)橫表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論