使用以下sqlfiddle here如何使用case语句查找2012-04-1
和2012-03-31
月份之间的最近一次付款,如同之前的查询一样
我试过这个:
max(case when py.pay_date >= STR_TO_DATE(CONCAT(2012, '-04-01'),'%Y-%m-%d') and py.pay_date <= STR_TO_DATE(CONCAT(2012, '-03-31'), '%Y-%m-%d') + interval 1 year then py.amount end) CURRENT_PAY
然而,我得到的答案是错误的,实际答案应该是:(12, '2012-12-12', 20, 1)
请给我一些帮助,谢谢。
答案 0 :(得分:2)
该条件属于CASE
子句,而不是MAX()
聚合中的WHERE
。这会加入一个子查询,该子查询通过加入person_id
来提取每MAX(pay_date), person_id
次最近的付款。
SELECT payment.*
FROM
payment
JOIN (
SELECT MAX(pay_date) AS pay_date, person_id
FROM payment
WHERE pay_date BETWEEN '2012-04-01' AND DATE_ADD('2012-03-31', INTERVAL 1 YEAR)
GROUP BY person_id
) maxp ON payment.person_id = maxp.person_id AND payment.pay_date = maxp.pay_date
这里是an updated fiddle,你的表中已经更正了id(因为它们中有一堆是15)。这将返回2013-03-28
的记录18。
在看到正确的 SQL小提琴后...要将此查询的结果合并到现有查询中,您可以LEFT JOIN
将其作为p.id
上的子查询。
select p.name,
v.v_name,
sum(case when Month(py.pay_date) = 4 then py.amount end) april_amount,
(case when max(py.pay_date)and month(py.pay_date)= 4 then py.amount else 0 end) max_pay_april,
sum(case
when Month(py.pay_date) = Month(curdate())
then py.amount end) current_month_amount,
sum(case
when Month(py.pay_date) = Month(curdate())-1
then py.amount end) previous_month_amount,
maxp.pay_date AS last_pay_date,
maxp.amount AS last_pay_amount
from persons p
left join vehicle v
on p.id = v.person_veh
left join payment py
on p.id = py.person_id
/* LEFT JOIN against the subquery: */
left join (
SELECT MAX(pay_date) AS pay_date, amount, person_id
FROM payment
WHERE pay_date BETWEEN '2012-04-01' AND DATE_ADD('2012-03-31', INTERVAL 1 YEAR)
GROUP BY person_id, amount
) maxp ON maxp.person_id = p.id
group by p.name,
v.v_name