sqlserver 縱橫

來源:互聯網
上載者:User

標籤:

縱錶轉橫表
create table Score(            Name nvarchar(128),    Class nvarchar(128),    score int)insert into Score(Name, Class, score)values(‘張三‘,‘語文‘,98)insert into Score values(‘張三‘,‘語文‘,98)insert into Score values(‘張三‘,‘數學‘,89)insert into Score values(‘張三‘,‘物理‘,78)insert into Score values(‘李四‘,‘語文‘,79)insert into Score values(‘李四‘,‘數學‘,88)insert into Score values(‘李四‘,‘物理‘,100)select * from Scoreselect t.Name,SUM(case t.Class when ‘語文‘ then t.score else 0 end) as 語文,SUM(case t.Class when ‘數學‘ then t.score else 0 end) as 數學,SUM(case t.Class when ‘物理‘ then t.score else 0 end) as 物理,SUM(case t.Class when ‘外語‘ then t.score else 0 end) as 外語,SUM(case t.Class when ‘政治‘ then t.score else 0 end) as 政治,SUM(case t.Class when ‘體育‘ then t.score else 0 end) as 體育from Score as tgroup by t.Name

 

橫錶轉縱表
-- 轉換的表插入新表select t.Name,SUM(case t.Class when ‘語文‘ then t.score else 0 end) as 語文,SUM(case t.Class when ‘數學‘ then t.score else 0 end) as 數學,SUM(case t.Class when ‘物理‘ then t.score else 0 end) as 物理into ScoreHbfrom Score as tgroup by t.Nameselect * from dbo.ScoreHb-- union all連結3個科目select t.Name,‘語文‘ as Class,t.語文 as scorefrom ScoreHb as tunion allselect t.Name,‘數學‘ as Class,t.數學 as scorefrom ScoreHb as tunion allselect t.Name,‘物理‘ as Class,t.物理 as scorefrom ScoreHb as torder by t.Name desc

 

pivot縱錶轉橫表
select    t2.Name,    t2.數學,    t2.物理,    t2.語文from Score as t1pivot (sum(score) for Class in(數學,語文,物理)) as t2
unpivot 橫錶轉縱表
 select *fromScoreHb unpivot (分數 for 課程 in (語文,數學,物理)) as t4

 

sqlserver 縱橫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.