Group by id having max(date_field)

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

To build a report, I must select some information on the last transaction status of all my customers. Until now, this is what I got:

SELECT c.firstname, c.lastname, d.product_name, o.payment, s.name, h.date_add FROM ps_orders o INNER JOIN ps_order_detail d ON d.id_order = o.id_order INNER JOIN ps_customer c ON c.id_customer = o.id_customer INNER JOIN ps_order_history h ON o.id_order = h.id_order INNER JOIN ps_order_state_lang s ON s.id_order_state = h.id_order_state WHERE s.id_lang =6 GROUP BY c.id_customer HAVING MAX(h.date_add) 

For each customer, this query is selecting the first date (the field h.date_add) when I need of the last one. It seems the MySQL is ignoring the HAVING.

I tried to make a sub-select, but it doesn't work too.

Thanks any answer.

回答1:

Here, you need to have a subquery which gets the latest date_add for every id_order on table ps_order_history. The result of the subquery is then joined back on the original table ps_order_history provided that it macth on two columns: date_add and id_order.

SELECT  c.firstname,          c.lastname,          d.product_name,          o.payment,          s.name,          h.date_add FROM    ps_orders o         INNER JOIN ps_order_detail d ON d.id_order = o.id_order         INNER JOIN ps_customer c ON c.id_customer = o.id_customer         INNER JOIN ps_order_history h ON o.id_order = h.id_order         INNER JOIN           (             SELECT  id_order, MAX(date_add) max_date             FROM    ps_order_history             GROUP   BY id_order         ) x ON  h.id_order = x.id_order AND                 h.date_add = x.max_date         INNER JOIN ps_order_state_lang s ON s.id_order_state = h.id_order_state WHERE   s.id_lang =6 GROUP   BY c.id_customer 


回答2:

To get the last date, you need to join it in:

SELECT c.firstname, c.lastname, d.product_name, o.payment, s.name, h.date_add FROM ps_orders o INNER JOIN ps_order_detail d ON d.id_order = o.id_order INNER JOIN ps_customer c ON c.id_customer = o.id_customer INNER JOIN ps_order_history h ON o.id_order = h.id_order INNER JOIN ps_order_state_lang s ON s.id_order_state = h.id_order_state inner join (select o.id_customer, max(oh.date_add) as maxdate from ps_order_history h join ps_order o on h.id_order = o.id_order group by o.id_customer) omax on omax.id_customer = o.id_customer and o.date_add = omax.maxdate WHERE s.id_lang =6 GROUP BY c.id_customer 

Your having clause calculates the maximum date and then succeeds when it is not equal to 0 (which would be most of the time).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!