mysql 竖表变横表 例子

来源:互联网 发布:python抓取手机号 编辑:程序博客网 时间:2024/06/05 08:04
  1. table1
  2.  
  3. 月份mon 部门dep 业绩yj
  4. -------------------------------    
  5. 一月份 01 10
  6. 一月份 02 10
  7. 一月份 03 5
  8. 二月份 02 8
  9. 二月份 04 9
  10. 三月份 03 8
  11.  
  12. table2
  13.  
  14. 部门dep 部门名称dname
  15. --------------------------------
  16. 01 国内业务一部
  17. 02 国内业务二部
  18. 03 国内业务三部
  19. 04 国际业务部
  20.  
  21. table3 (result)
  22.  
  23. 部门dep 一月份     二月份   三月份
  24. --------------------------------------    
  25.     01         10           null        null    
  26.     02         10            8          null
  27.     03        null           5            8
  28.     04        null          null          9
  29.  
  30. ------------------------------------------    
  31. 1)
  32. select a.部门名称dname,b.业绩yj as '一月份',c.业绩yj as '二月份',d.业绩yj as '三月份'
  33. from table1     a,table2 b,table2 c,table2 d
  34. where a.部门dep = b.部门dep and b.月份mon = '一月份' and
  35. a.部门dep = c.部门dep and c.月份mon = '二月份' and
  36. a.部门dep = d.部门dep and d.月份mon = '三月份' and
  37. 2)
  38. select a.dep,    
  39. sum(case when     b.mon=1 then b.yj else 0 end) as '一月份',
  40. sum(case when     b.mon=2 then b.yj else 0 end) as '二月份',
  41. sum(case when     b.mon=3 then b.yj else 0 end) as '三月份',
  42. sum(case when     b.mon=4 then b.yj else 0 end) as '四月份',
  43. sum(case when     b.mon=5 then b.yj else 0 end) as '五月份',
  44. sum(case when     b.mon=6 then b.yj else 0 end) as '六月份',
  45. sum(case when     b.mon=7 then b.yj else 0 end) as '七月份',
  46. sum(case when     b.mon=8 then b.yj else 0 end) as '八月份',
  47. sum(case when     b.mon=9 then b.yj else 0 end) as '九月份',
  48. sum(case when     b.mon=10 then b.yj else 0 end) as '十月份',
  49. sum(case when     b.mon=11 then b.yj else 0 end) as '十一月份',
  50. sum(case when     b.mon=12 then b.yj else 0 end) as '十二月份',
  51. from table2 a     left join table1 b on a.dep=b.dep

 

原创粉丝点击