根据条件在同一列和同一列上执行减法

时间:2014-10-07 07:12:45

标签: php mysql

我有一个具有以下结构的表:

employeeid  SalaryType  Amount
------------------------------
100         w           200
100         s           100
210         w           300
210         s           50
300         w           90
300         s           30

根据这些条目,我想检索以下结果:

emloyeeid   Amount (difference between W and S)
-----------------------------------------------
100         100
210         250
300         60

我如何实现这一结果?

2 个答案:

答案 0 :(得分:1)

例如......

SELECT t1.employeeid, t1.amount - t2.amount FROM 
  (SELECT * FROM tablename WHERE salaryType = 'w') t1,
  (SELECT * FROM tablename WHERE salaryType = 's') t2
WHERE t1.employeeid = t2.employeeid  

答案 1 :(得分:0)

您可以使用LEFT JOIN来解决问题

SELECT employeeid, t1.amount - t2.amount FROM
mytable AS t1 LEFT JOIN mytable AS t2 
ON t1.employeeid = t2.employeeid 
AND t1.SalaryType = 'w' AND t2.SalaryType = 's'