話不多說直接進入正題
資料接庫資料如下圖:
要把資料變成行,一目了然的看到乙個學生的所有科目成績,sql如下:
執行結果如下:select name,
max(case subject when '語文' then score else 0 end) as '語文',
max(case subject when '數學' then score else 0 end) as '數學',
max(case subject when '英語' then score else 0 end) as '英語',
max(case subject when '生物' then score else 0 end) as '生物'
from studentscores
group by name
這裡解釋一下sql,查詢的時候用case when then選擇需要進行轉行的字段以及字段結果,即當subject是xx的時候選擇subject對應的score作為subject的成績,這裡需要注意case when then的結果要用max函式包裹,不然結果也會變成行,但是每行只有一科的成績,用max包裹就是選擇最大成績,把多行合併成一行完成行轉列。
再舉個栗子吧
資料庫資料如下:
要求按日期、支付方式來統計充值金額資訊,sql如下:
sql的執行結果如下:select time,
case type when '支付寶' then sum(money) else 0 end as '支付寶',
case type when '雲閃付' then sum(money) else 0 end as '雲閃付',
case type when '信用卡' then sum(money) else 0 end as '信用卡'
from game
group by time, type
這個結果也只是統計出了不同時間,不同型別的充值,雖然行轉列了,但是每行只有乙個欄位有資料,如果需要做統計還需要再進行處理,處理sql如下:
同過對第一次sql的再一次求和,完成了去除0值,結果如下:select time,
sum(支付寶) as 支付寶,
sum(雲閃付) as 雲閃付,
sum(信用卡) as 信用卡
from
(select time,
case type when '支付寶' then sum(money) else 0 end as '支付寶',
case type when '雲閃付' then sum(money) else 0 end as '雲閃付',
case type when '信用卡' then sum(money) else 0 end as '信用卡'
from game group by time, type) a
group by time
資料庫動態行轉列
1 棧stack.peek 表示的是取得棧頂元素值,但不將其彈出。2 sql語句 動態行轉列 string sql1 declare strsql varchar 8000 set strsql select stuname 姓名 string sql2 sql1 select strsql str...
資料庫 SQL 行轉列
學校裡面記錄成績,每個人的選課不一樣,而且以後會新增課程,所以不需要把所有課程當作列。資料庫grade裡面資料如下圖,假定每個人姓名都不一樣,作為主鍵。本文以mysql為基礎,其他資料庫會有些許語法不同。資料庫資料 處理後效果 方法一 select distinct a.name,select sc...
MySQL資料庫行轉列
一 資料來源如下所示 二 對應sql語句如下所示 行轉列 select t1.產品名稱 sum case t1.日期 when 2019 11 11 then t1.數量 else 0 end as 2019 11 11 sum case t1.日期 when 2019 11 12 then t1....