MySQL資料庫行轉列

2022-06-18 09:24:15 字數 888 閱讀 1723

一、資料來源如下所示

二、對應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.`數量` else 0 end) as '2019-11-12',

sum(case t1.`日期` when '2019-11-13' then t1.`數量` else 0 end) as '2019-11-13',

sum(case t1.`日期` when '2019-11-14' then t1.`數量` else 0 end) as '2019-11-14',

sum(case t1.`日期` when '2019-11-15' then t1.`數量` else 0 end) as '2019-11-15',

sum(case t1.`日期` when '2019-11-16' then t1.`數量` else 0 end) as '2019-11-16',

sum(case t1.`日期` when '2019-11-17' then t1.`數量` else 0 end) as '2019-11-17'

from sheet2 t1 group by t1.`產品名稱` limit 0, 1000;

三、最終結果如下所示

資料庫行轉列

話不多說直接進入正題 資料接庫資料如下圖 要把資料變成行,一目了然的看到乙個學生的所有科目成績,sql如下 select name,max case subject when 語文 then score else 0 end as 語文 max case subject when 數學 then s...

資料庫動態行轉列

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...