最近的条目基于一年间隔mysql表

时间:2012-09-02 20:37:51

标签: mysql

使用以下sqlfiddle here如何使用case语句查找2012-04-12012-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)

请给我一些帮助,谢谢。

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