我有一个mysql问题我试图找到最新的付款值,并且,在特定的月份(在此查询中我使用四月)。链接到sqlfillde的是here
(case when max(py.pay_date)and month(py.pay_date)= 4 then amount else 0 end) max_pay_april,
这就是我所拥有的,但似乎并没有起作用。最新的付款金额为:(5, '2012-04-20', 90,)
因此90
我会非常感谢您的帮助。
答案 0 :(得分:3)
这个怎么样:
select p.name,
v.v_name,
sum(case when Month(py.pay_date) = 4 then amount end) april_amount,
max(case
when month(py.pay_date)= 4
and py.pay_date = (select max(pay_date)
from payment
where month(pay_date) =4 )
then amount else 0 end) max_pay_april,
sum(case
when Month(py.pay_date) = Month(curdate())
then amount end) current_month_amount,
sum(case
when Month(py.pay_date) = Month(curdate())-1
then amount end) previous_month_amount
from persons p
left join vehicle v
on p.id = v.person_veh
left join payment py
on p.id = py.person_id
group by p.name,
v.v_name