从calculate和group by获取最后一个数据查询

时间:2016-09-23 03:34:17

标签: mysql

我正在尝试使用总帐数据进行试算平衡,可以从最后一个基于计算的借记贷方帐户名称中进行试算结果,然后根据每个帐户名称进行分组

GEneral分类帐: 卡斯:

Account  |  Debet  | KRedit  | Saldo 
kas         1000      0        1000
kas         200       0        1200
kas         0         250       950 

银行:

Account  |  Debet  | KRedit  | Saldo 
bank        2000      0        2000
bank         200       0        2200
bank         0         500      1700 

销售:

Account  |  Debet  |  KRedit  |   Saldo 
Sale          0        2000      -2000
Sale           0        500       -2500
Sale           0        500       -3000

结果:

Account  |  Debet  |  KRedit  |    
    Kas       950        0      
    bank      1700      0       
    sale       0        3000     

有我的代码:

SELECT nama_perkiraan,kredit,debet,max(@s:=@s+debet-kredit) as saldo FROM `tbl_jurnal_umum` LEFT JOIN (SELECT @s:=0) as `setVar` ON 1=1  GROUP by nama_perkiraan

谢谢

1 个答案:

答案 0 :(得分:0)

    sselect s.account,
         case when s.saldo > 0 then s.saldo else 0 end as debet ,
         case when s.saldo < 0 then s.saldo * -1 else 0 end as kredit 
from
(
select account,
        sum(case when debet <> 0 then debet else kredit * -1 end) saldo
from generalledger
group by account
) s
where s.saldo <> 0
order by 
case when s.account = 'kas' then 1
      when s.account = 'bank' then 2
      else 3
end