MySQL从分组中减去两个行值

时间:2019-12-05 15:59:13

标签: mysql sql

我正在使用以下查询将结果分为两行以获取收入和扣除额。

select t2.type
     , sum(t1.amount) as total_earnings 
  from employee_pay_elements t1
  join pay_elements t2 
    on (t1.pay_element_id = t2.id)
 group 
    by t2.type

和结果

enter image description here

现在,我需要获得差异(收入-扣除额),如何轻松有效地获得差异?

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

function parseSoapTypes(\SoapClient $soap): array {
    $types = $soap->__getTypes();
    $types_parsed = [];
    $regex = '/^\s(\w*?)\s(\w*?);/mi';
    $regex_struct = '/struct\s(.*?)\s/';
    foreach ($types as $type) {
        preg_match($regex_struct, $type, $match_struct);
        $struct = isset($match_struct[1]) ? $match_struct[1] : [];
        preg_match_all($regex, $type, $matches);
        if (isset($matches[1]) && isset($match_struct[1])) {
            $types_parsed[$struct] = array_combine($matches[2], $matches[1]);
        }
    }
    return $types_parsed;
}