Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Client list with last order

I have two tables, Cients and Orders and I’m try to create a list with client / last order date

CLIENTS
client_id | client_name
1         | Mark
2         | John
3         | Paul
4         | Sid

ORDERS
order_id | order_client_id | last_order_date
1        | 1               | 2022-01-01
2        | 2               | 2022-01-03
3        | 4               | 2022-01-04

If I’m using a LEFT JOIN results are partials, because Paul not have orders and this one not appear on list.

   SELECT  *
     FROM  clients
LEFT JOIN orders ON order_client_id = client_id
    WHERE client_role = ?


// CURRENT RESULTS
Mark   2022-01-01
John   2022-01-03
Sid    2022-01-04

I’m like to obtain a full client list and if someone not have an order, date remain blank

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// EXPECTED RESULTS
Mark   2022-01-01
John   2022-01-03
Paul   
Sid    2022-01-04

>Solution :

Better check it out on SQLFiddle.

Select c.client_name, last_order_date From clients c
Left Join (select order_client_id, max(last_order_date) as last_order_date 
from orders group by order_client_id) o on o.order_client_id = c.client_id;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading