My issue with SQL function, is that I often mix SUM / COUNT, or even where I can put a WHERE clause and a GROUP BY, short version, SQL is one of my flaws.
Ok, now here’s my current issue, I need to make a SQL function (in my PHP Model) that get the number of order I had "today" and their total cost, but I need to separate the result by country (sorry for my english) , for example the result I want should look like this (let’s say I had 20 orders today) :
U.S : 15 orders (for a total of 288$) , CANADA : 5 orders (for a total of 94$)
I tried many things, and the only two that didn"t give me an error were these two (but far from the result I need) :
SELECT sum(o.amount) AS totalmoney, p.name, p.id, p.name_clean, p.iso_code
FROM orders AS o
LEFT JOIN customers AS c ON o.id_customer = c.id
LEFT JOIN countries AS p ON c.country = p.id
WHERE DATE(o.date_create) = CURDATE()
SELECT sum(o.amount) AS totalmoney, o.date_create, p.name, COUNT(p.id) AS totalpays,
p.name_clean, p.iso_code, c.country
FROM orders AS o
LEFT JOIN customers AS c ON o.id_customer = c.id
LEFT JOIN countries AS p ON c.country = p.id
GROUP BY o.date_create
My three tables are (table name : column usefull) :
countries : id – name
customers : id – country_id
orders : id – id_customer – amount ($) – date_create
Can you please help me?
Thank you for your time.
————- EDIT WITH THE ANSWER I USED —————
Thanks to everyone who participate and helped me to have a better understanding of SQL.
SELECT sum(orders.amount) total, countries.name
FROM orders
INNER JOIN customers ON orders.id_customer = customers.id
INNER JOIN countries ON countries.id = customers.country_id
WHERE orders.date_create = ?
GROUP BY customers.id
It’s exactly what I needed.
4
Answers
This should do what you want it to do:
Try with that:
— PostgreSQL
You’re wanting to group by country on a certain date, therefore your group by is country, and the where is the date:
Inner join is appropriate here, because the joins should only produce a single row for customer and country per order.
you can use
over
whithsum
andcount
here is a db<>fiddle with some pseudo data.
this will also get the data group by created date which match the OP need more imo.
pros with window function :
over
is that you can have different aggregate function with different ‘condition’ and don’t need togroup by
every non aggregate column which usually lead to a lot of subqueries.