如何求和字段并使用不同的id创建两个不同的字段

时间:2013-09-19 07:35:44

标签: mysql

我的查询有问题我在下面有一个表截图,调用ob和emp_data表

我希望根据obCo = 5得到字段“date”的总和为liv,并且基于obCo = 6得到相同字段的另一个和。这是我的询问。

select ob.obNo,
  SUM(ob.date) as liv,
  ob.empId,
  ob.obDesc,    
  ob.lugar,
  ob.sponsor,
  ob.dFile,
  ob.obCo,
  emp_data.lname,
  emp_data.fname
from emp_data 
inner join ob on ob.empId=emp_data.emp_id
where obCo=5  
  and dFile >= '$year/05/01' 
  and dFile <='$nyear/04/31' and ak_id=1
group by ob.empId
order by lname ASC

1 个答案:

答案 0 :(得分:0)

总结一个IF()表达式。

select ob.obNo,
  SUM(if (obCo = 5, ob.date, 0)) as liv,
  SUM(if (obCo = 6, ob.date, 0)) as late,
  ob.empId,
  ob.obDesc,    
  ob.lugar,
  ob.sponsor,
  ob.dFile,
  ob.obCo,
  emp_data.lname,
  emp_data.fname
from emp_data 
inner join ob on ob.empId=emp_data.emp_id
where obCo IN (5, 6)
  and dFile >= '$year/05/01' 
  and dFile <='$nyear/04/31' and ak_id=1
group by ob.empId
order by lname ASC

SQLFIDDLE DEMO