SQL開發技巧:開發技巧
阿新 • • 發佈:2017-12-18
class enc esc substring images eat 技術分享 blog money
一、行列轉換
基本思路:
1. 將數據轉轉為標書數據,如圖所示
2. 使用笛卡爾積做行列轉換
select sum(case when childr=‘餐飲‘ then money end ) as ‘餐飲‘ , sum(case when childr=‘通訊‘ then money end ) as ‘通訊‘ , sum(case when childr=‘娛樂‘ then money end ) as ‘娛樂‘ from (select childr, convert(sum(money), decimal(10,2)) as money from wx_spend group by childr) tmp;
一、單列轉多行轉換
原數據樣式
處理後數據樣式
SQL語句
CREATE TABLE tmp_sequence (id INT PRIMARY KEY AUTO_INCREMENT); INSERT INTO tmp_sequence VALUES(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(); SELECT name,REPLACE(SUBSTRING(SUBSTRING_INDEX(courseinfo, ‘,‘, a.id), CHAR_LENGTH(SUBSTRING_INDEX(courseinfo, ‘,‘, a.id-1)) + 1), ‘,‘ ,‘‘) AS courseinfo FROM tmp_sequence a CROSS JOIN (SELECT name, concat(courseinfo,",") AS courseinfo, LENGTH(courseinfo) - LENGTH(REPLACE(courseinfo, ‘,‘, ‘‘)) + 1AS size FROM W_SalesCoursePackageInfo LIMIT 1,1) b ON a.id <= b.size
SQL開發技巧:開發技巧