如何以这种方式格式化mysql表?

时间:2012-09-02 06:14:16

标签: php mysql

说我有这样一张桌子:

emp_id  work_site   expenses
001     atlanta     $500
001     atlanta     $750
002     boston      $750
002     chicago     $250
003     chicago     $500
003     chicago     $500

现在我想按照以下格式对emp_id和唯一城市的费用进行分组:

emp_id  atlanta boston  chicago
001     $1250    $0     $0
002     $0       $750   $250
003     $0       $0     $1000

在mysql或PHP中执行此操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

你可以使用它进行转动,如果费用不是

,你需要先将费用转换为数字
 select emp_id
,SUM(CASE  WHEN work_site ='atlanta' THEN expenses else 0 END) as 'atlanta'
,SUM(CASE  WHEN work_site ='boston' THEN expenses else 0 END) as 'boston'
,SUM(CASE  WHEN work_site ='chicago' THEN expenses else 0 END) as 'chicago'
from Table1
group by emp_id

SQL FIDDLE http://sqlfiddle.com/#!2/dd535/1/0

答案 1 :(得分:3)

简单地说,你可以这样做:

  SELECT emp_id, 
         SUM( if( work_site = 'atlanta', expenses , 0 ) ) AS 'atlanta',  
         SUM( if( work_site = 'boston', expenses , 0 ) ) AS 'boston', 
         SUM( if( work_site = 'chicago', expenses , 0 ) ) AS 'chicago' 
  FROM your_table
  GROUP BY emp_id