How to sum columns from two related tables - mysql

I have two tables. Invoices and invoice_items. I am trying to get the sum of total_payment and total quantity for each client. I tried this query:
SELECT client_id,
sum(total_amount), sum(it.quantity) as days_hired
FROM `invoices` `iv`
join invoice_items it on it.invoice_id=iv.invoice_id
group by client_id, it.invoice_id
But for client_id 14, I am getting total payment as 1908 instead of 636. Looks like the sum of this column gets repeated for every invoie_item. Any help will be appreciated.
invoices
invoice_id client_id total_payment
36 13 530
38 14 636
invoice_items
invoice_id user_id quantity
36 2 2
38 3 2
38 4 2
38 5 2
Expected output:
13 530 2
14 636 6

You can try below -
SELECT client_id, sum(total_amount) as toal_amount, sum(it.quantity) as total_quantity
FROM `invoices` `iv`
join
(
select invoice_id,sum(quantity) as quantity from invoice_items group by invoice_id
)it on it.invoice_id=iv.invoice_id
group by client_id, it.invoice_id

Try:
select i.*, ii.total_quantity
from invoices i
join (
select invoice_id, sum(quantity) total_quantity from invoice_items
group by invoice_id
) ii on i.invoice_id = ii.invoice_id

Related

How to group rows in SQL by earliest date when are there are multiple rows with earliest date?

I am trying to come up with a query that will return the aggregate data for the earliest orders the customers have placed. What I cannot quite wrap my head around is how to construct this query when there are multiple orders placed on the same day for the earliest purchase date for customer 2.
customers
id
name
created_at
1
Sam
2019-07-12
2
Jimmy
2019-01-22
items
id
name
price
1
Watch
200
2
Belt
75
3
Wallet
150
orders
id
customer_id
item_id
created_at
1
1
1
2018-08-01
2
1
2
2018-08-11
3
2
1
2019-01-22
4
2
3
2019-01-22
5
2
2
2019-03-03
expected query
customer_id
name
first_purchase_date
n_items
total_price
1
Sam
2018-08-01
1
200
2
Jimmy
2019-01-22
2
350
I currently have the following query set up, but this query is grouping by the customer_id such that the total number of items and total price do not reflect the earliest orders.
SELECT
orders.customer_id,
customers.name AS name,
MIN(orders.created_at) AS first_purchase_date,
COUNT(*) as n_items,
SUM(items.price) as total_price
FROM orders
INNER JOIN customers
ON orders.customer_id = customers.id
INNER JOIN items
ON orders.item_id = items.id
GROUP BY
customers.id
my incorrect query
customer_id
name
first_purchase_date
n_items
total_price
1
Sam
2018-08-01
2
275
2
Jimmy
2019-01-22
3
425
I recreated the tables in a SQL Server environment but this should help...I hope as it gives you the query result you're looking for. The data is exactly the same but I'm using temporary tables so hence the # prefixes.
SELECT
#orders.customer_id,
#customer.name AS name,
#orders.created_at as first_purchase_date,
--MIN(#orders.created_at) AS first_purchase_date,
COUNT(*) as n_items,
SUM(#items.price) as total_price
FROM #orders
INNER JOIN #customer
ON #orders.customer_id = #customer.id
INNER JOIN #items
ON #orders.item_id = #items.id
inner join
(
select customer_id, name, MIN(first_purchase_date) as
first_purchase_date
from
(
SELECT
#orders.customer_id,
#customer.name AS name,
#orders.created_at as first_purchase_date,
--MIN(#orders.created_at) AS first_purchase_date,
COUNT(*) as n_items,
SUM(#items.price) as total_price
FROM #orders
INNER JOIN #customer
ON #orders.customer_id = #customer.id
INNER JOIN #items
ON #orders.item_id = #items.id
group by #orders.customer_id,#customer.name, #orders.created_at
)base
group by customer_id, name
) firstorders
on
#customer.id = firstorders.customer_id
and
#customer.name = firstorders.name
and
#orders.created_at = firstorders.first_purchase_date
group by
#orders.customer_id,#customer.name, #orders.created_at

name and sum from 2 different tables

I have 2 tables.
table customer have. id , name , age
table order have . id, customer_id , order_amount , order date.
I want to show all name from customer table and sum of order amount from order table according to customer.
customer_id
Name
age
1
Alice
24
2
Bob
52
3
Carol
45
4
Dave
51
order_id
customer_id
order_amount
order_date
1
2
50
2012-4-5
2
1
27
2012-8-1
3
2
12
2013-5-20
4
4
25
2014-1-25
5
4
30
2014-5-30
6
1
20
2014-6-22
EDIT
I tried this but it gives me only bob and sum of all columns instead of separate sum of customers
SELECT customers.name, SUM(orders.order_amount) FROM `orders` INNER JOIN customers WHERE orders.customer_id = customers.customer_id;
Joining condition must be on ON clause, not in WHERE.
You must specify for what group the sum must be calculated.
SELECT customers.name, SUM(orders.order_amount)
FROM `orders`
INNER JOIN customers ON orders.customer_id = customers.customer_id
GROUP BY customers.name;

How to get right sum from inner join in mysql

I have two tables one is orders and second is order_product in which I have to find out orders count, product count, totalamount in corresponding to store using store id from which I have successfully find out the orders count and product count but my totalamount is not coming correct.
orders:
...........................
order_id or_total_amt
...........................
1 10
2 10
3 10
order_product
.................................
op_id op_order_id st_id
.................................
1 1 1
2 2 2
3 3 1
4 3 1
I want below output but my totalamount value is coming wrong it is coming 30,but the correct value is 20 which i have mentioned in the right output below.
output which i want:
.........................................
st_id orders product totalmount
.........................................
1 2 3 20
2 1 1 10
I have tried the below query which is giving 30 value of totalamount which is wrong.
SELECT `op_st_id`,count(distinct orders.`order_id`)as orders,count(order_product.op_pr_id) as product
,sum(orders.or_total_amt) as totalamount from orders
inner JOIN order_product on orders.order_id=order_product.op_order_id
group by `op_st_id`
SELECT
`st_id`,
count(DISTINCT orders.`order_id`) AS orders,
count(order_product.op_id) AS product,
count(DISTINCT orders.`order_id`)*(sum(orders.or_total_amt)/count(order_product.op_id)) AS totalamount
FROM
orders
INNER JOIN order_product ON orders.order_id = order_product.op_order_id
GROUP BY
`st_id`

sql grouping finding average

i am looking to find the avg cost for the total cost of each order but my grouping function is invalid
SELECT AVG(SUM(quantityOrdered*priceEach)) AS total
FROM orderdetails od
GROUP BY orderNumber
below is a snippet of my database
orderNumber productCode quantityOrdered priceEach orderLineNumber
10100 S24_3969 49 35.29 1
10101 S18_2325 25 108.06 4
10101 S18_2795 26 167.06 1
10101 S24_1937 45 32.53 3
10101 S24_2022 46 44.35 2
10102 S18_1342 39 95.55 2
10102 S18_1367 41 43.13 1
10103 S10_1949 26 214.3 11
10103 S10_4962 42 119.67 4
10103 S12_1666 27 121.64 8
10103 S18_1097 35 94.5 10
10103 S18_2432 22 58.34 2
10103 S18_2949 27 92.19 12
10103 S18_2957 35 61.84 14
10103 S18_3136 25 86.92 13
10103 S18_3320 46 86.31 16
It's invalid use cannot use two aggregate functions together
SELECT SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
Having SUM(quantityOrdered*priceEach)>(SELECT AVG(quantityOrdered*priceEach) FROM orderdetails)
Just calculate the average using sum() divided by a number:
SELECT SUM(quantityOrdered*priceEach) / COUNT(DISTINCT orderNumber) AS total
FROM orderdetails od ;
You do it in two steps.
SQL Fiddle Demo
Calculate the Total of each order.
SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
Calculate the Average between all the totals
SELECT AVG(total)
FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
) T
EDIT: I miss the last step after checking Ritesh answer.
SELECT o.*, t.global_avg
FROM (SELECT orderNumber, SUM(quantityOrdered*priceEach) AS order_total
FROM orderdetails od
GROUP BY orderNumber) o
CROSS JOIN
(SELECT AVG(total) global_avg
FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
) t
) t
WHERE o.order_total > t.global_avg;
OUTPUT:

How to apply aggregate function only on distinct records

I have two tables, orders and order_item.
orders table:
Id Total DeliveryCharge Status DeliveryDate
2001 600 120 30 2015-09-01 11:56:32
2002 1500 150 30 2015-09-09 09:56:32
2003 1200 100 30 2015-09-30 08:05:32
order_item table:
Id OrderTotal Quantity
12001 2001 2
12002 2001 1
12003 2002 1
12004 2003 1
12005 2003 1
As each order can contain multiple products, that way order_item table could multiple records for a single order.
I want to get result by the query is
OrderCount Quantity OrderTotal DeliveryCharge
3 6 3300 370
I wrote a query
select count(distinct od.Id) as OrderCount,
sum(oi.Quantity) as Quantity,
(select sum(ord.OrderTotal) from orders ord
where ord.DeliveryDate between '2015-09-01' and '2015-10-01' and ord.Status=30 ) as OrderTotal
from orders od
join Order_items oi on od.Id=oi.orderId
where od.Status=30
and od.DeliveryDate between '2015-09-01' and '2015-10-01'
which has the result
OrderCount Quantity OrderTotal
3 6 3300
But now I want the sum of DeliveryCharge of orders table, so again I have to write select sub-query as I wrote for OrderTotal.
Is there a good way to find it with single query without using multiple sub-queries?
Put subqueries in the from clause:
select o.OrderCount, o.OrderTotal, o.OrderDeliveryCharge, oi.quantity
from (select count(*) as OrderCount, sum(Total) as OrderTotal,
sum(DeliveryCharge) as OrderDeliveryCharge
from orders
) o cross join
(select sum(quantity) as quantity
from order_item
) oi;
Use this
SELECT SUM(oi.oc) AS 'OrderCount', SUM(oi.q) AS 'Quantity', SUM(o.total) AS 'OrderTotal', SUM(o.deliverycharge) AS 'DeliveryCharge'
FROM
orders o INNER JOIN
(SELECT ordertotal, COUNT(DISTINCT(ordertotal)) AS oc, SUM(quantity) AS q FROM order_item GROUP BY 1) oi ON o.id=oi.ordertotal