SQL語句實現行轉列查詢

2022-08-20 11:48:10 字數 1783 閱讀 9507

表sales 

查詢結果如下:

1、建表 

create table [dbo].[sales](

[id] [int] identity(1,1) not null,

[year] [int] null,

[jidu] [int] null,

[jine] [int] null,

primary key clustered

( [id] asc

)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]

) on [primary]

2、插入資料

insert into sales(year, jidu, jine) values(1991,1,11)

insert into sales(year, jidu, jine) values(1991,2,22)

insert into sales(year, jidu, jine) values(1991,3,33)

insert into sales(year, jidu, jine) values(1991,4,44)

insert into sales(year, jidu, jine) values(1992,1,55)

insert into sales(year, jidu, jine) values(1992,2,66)

insert into sales(year, jidu, jine) values(1992,3,77)

insert into sales(year, jidu, jine) values(1992,4,88)

有兩種解決方法: 

一、使用case when 實現:

select

year as '年份',

max(case jidu when 1 then jine end) as '第一季度',

max(case jidu when 2 then jine end) as '第二季度',

max(case jidu when 3 then jine end) as '第三季度',

max(case jidu when 4 then jine end) as '第四季度'

from sales group by year

二、使用pivot函式: 

使用pivot函式時須注意對公升級到 sql server 2005 或更高版本的資料庫使用 pivot 和 unpivot 時,必須將資料庫的相容級別設定為 90 或更高。 

語法介紹參考如下**: 

sql語句如下:

select year as 年份,[1] as 第一季度,[2] as 第二季度,[3] as 第三季度,[4] as 第四季度

from (select year,jidu,jine from sales) as t1 pivot (sum(jine) for jidu in ([1],[2],[3],[4])) as a --'t1'和'a'這兩個別名必須得有要不會報錯。

執行結果如下:

mysql 查詢行轉列 SQL語句實現行轉列查詢

表sales 查詢結果如下 1 建表 create table dbo sales id int identity 1,1 not null,year int null,jidu int null,jine int null,primary key clustered id asc with pad...

SQL實現行轉列

需求 用sql實現行轉列。如下圖所示 行顯示的資料轉換成列顯示 實現行轉列的sql指令碼如下 select date format last day date format now y m d y m d as 業務日期,max case index code when ind20101001 th...

sql實現行轉列

行轉列不留空 select a as 訂單號 四川 as 位址 into result insert into result select a as 訂單號 成都 as 位址 union all select b as 訂單號 新疆 as 位址 union all select b as 訂單號 喀...