Below you can see my SQL query
select c.email_address,o.order_id as "Number of Orders",
((oi.item_price-oi.discount_amount)*oi.quantity) as "Total amount"
from customers c
inner join orders o on c.customer_id=o.customer_id
inner join order_items oi on o.order_id=oi.order_id
From that, I can get output like below
Email Orders_id Amount
allan@yahoo.com 1 839.3
barryz@gmail.com 2 303.79
allan@yahoo.com 3 1208.16
allan@yahoo.com 3 253.15
chrisb@gmail.com 4 1678.6
david@hotmail.com 5 299
erinv@gmail.com 6 299
frank@gmail.com 7 489.3
frank@gmail.com 7 559.9
frank@gmail.com 7 489.99
garyz@yahoo.com 8 679.99
david@hotmail.com 9 489.3
But I want to customize it like below
Email Number of Orders Total Amount
allan@yahoo.com 3 2300.61
barryz@gmail.com 1 303.79
chrisb@gmail.com 1 1678.6
david@hotmail.com 2 788.3
erinv@gmail.com 1 299
frank@gmail.com 3 1539.19
garyz@yahoo.com 1 679.99
Can anyone help me to do this?
>Solution :
As you said in the question, use GROUP BY and aggregate the number of orders and the total:
select c.email_address,
COUNT(o.order_id) as "Number of Orders",
SUM((oi.item_price-oi.discount_amount)*oi.quantity) as "Total amount"
from customers c
inner join orders o on c.customer_id=o.customer_id
inner join order_items oi on o.order_id=oi.order_id
GROUP BY c.email_address