1. 程式人生 > >SQL開發技巧:開發技巧

SQL開發技巧:開發技巧

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, ,, ‘‘)) + 1
AS size FROM W_SalesCoursePackageInfo LIMIT 1,1) b ON a.id <= b.size

SQL開發技巧:開發技巧