有時候需要做報表時,如何將一個字段年份劃分成12個月份呢?

select v_short_name, 
       sum(case when c_time = '201501' then n_amount else 0 end) as Jan,
       sum(case when c_time = '201502' then n_amount else 0 end) as Feb,
       sum(case when c_time = '201503' then n_amount else 0 end) as Mar,
       sum(case when c_time = '201504' then n_amount else 0 end) as Apr,
       sum(case when c_time = '201505' then n_amount else 0 end) as May,
       sum(case when c_time = '201506' then n_amount else 0 end) as Jun,
       sum(case when c_time = '201507' then n_amount else 0 end) as Jul,
       sum(case when c_time = '201508' then n_amount else 0 end) as Aug,
       sum(case when c_time = '201509' then n_amount else 0 end) as Sep,
       sum(case when c_time = '201510' then n_amount else 0 end) as Oct,
       sum(case when c_time = '201511' then n_amount else 0 end) as Nov,
       sum(case when c_time = '201512' then n_amount else 0 end) as Decn,
       sum(n_amount) as Total 
  from XXX

 group by v_short_name;


這個代碼可以實現這個功能。


上面的方法爲靜態,下面的方法爲動態:

SET @asql='';
    SELECT DISTINCT c_time,
    @asql:=CONCAT(@asql,CONCAT('MAX(CASE DATE(c_time) WHEN \'',DATE(c_time),'\' THEN n_amount ELSE 0 END) AS `',DATE(c_time)),'`,')
    FROM 表名;
    SET @asql=CONCAT('SELECT v_short_name 'LEFT(@asql,LENGTH(@asql)-1),' FROM 表名GROUP BY v_short_name');
      SELECT @asql;
      PREPARE stml FROM @asql;
      EXECUTE stml;

發佈了49 篇原創文章 · 獲贊 13 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章