SQL Server 中行轉列 列轉行

2021-07-25 16:02:22 字數 1902 閱讀 2547

行轉列:

create database test

on primary (

name='test.mdf',

filename='d:\\project\test.mdf',

size=10mb,

filegrowth=15%

)log on(

name='test.ndf',

filename='d:\\project\test.ldf',

size=3mb,

filegrowth=15%)go

use test

gocreate table score(

id int primary key identity(1,1),

name varchar(20) not null,

course varchar(5),

scores numeric(5,0))go

drop table score

insert into score

select '張三','語文',90.2union

select '張三','數學',85.7union

select '張三','英語',75union

select '李四','語文',55union

select '李四','英語',40union

select '李四','數學',59union

select '王五','語文',60union

select '王五','數學',70union

select '王五','英語',30

1.通過case  where  條件1 then  結果1     多分支語句

select name as 姓名,sum(case when course='語文' then scores else 0 end) as 語文成績

,sum(case when course='數學' then scores else 0 end) as 數學成績

,sum(case when course='英語' then scores else 0 end) as 英語成績

from score group by name

2.通過pivot

select * from score

pivot(max(scores) for course in(語文,數學,英語)) b

列轉行:

1.unpivot

create table pvt (vendorid int, emp1 int, emp2 int,

e*** int, emp4 int, emp5 int);

goinsert into pvt values (1,4,3,5,4,4);

insert into pvt values (2,4,1,5,5,5);

insert into pvt values (3,4,3,5,4,4);

insert into pvt values (4,4,2,5,5,4);

insert into pvt values (5,5,1,5,5,5);

go--unpivot the table.

select vendorid, employee, orders

from

(select vendorid, emp1, emp2, e***, emp4, emp5

from pvt) p

unpivot

(orders for employee in

(emp1, emp2, e***, emp4, emp5)

)as unpvt;

go

SQL中行轉列 列轉行

sql行轉列 列轉行 這個主題還是比較常見的,行轉列主要適用於對資料作聚合統計,如統計某類目的商品在某個時間區間的銷售情況。整理測試資料 create table wyc test id int 32 not null auto increment name varchar 80 default n...

MySQL中行轉列與列轉行

mysql中行轉列與列轉行 行轉列,即為將mysql中原本同一列 字段 下的內容轉換為同一行的多個字段。如上圖一張成績表,進行如下轉換 1 行轉列轉換後,轉換後,變為如下顯示 明顯可以看出,此時將userid分為了一組,每組都有語文 數學 英語 政治這幾門課的成績。方式一 用if語句轉換 selec...

hive中行轉列 列轉行的實現

行轉列實現 表資訊 場景一 使用concat ws和collect set函式 說明 collect set函式可以返回乙個array型別。concat ws函式可以拼接陣列,如下 場景二 有時候如果需要對指標字段求和,則上述sql改寫成如下 場景三 使用str to map和explode函式以及...