SQL count and sum issue - mysql

I have 2 tables with data.
The first table cus contains the customer data. The second table invoice contains the invoices created by the customer.
I want to select the total created invoices and the total sum of the invoices per customer.
Here is what I have:
SELECT cus.cus_id, cus.name_cus, count(invoice.id) as id2, CONCAT('€ ', ROUND(SUM(invoice.total),2)) as total, cus.id
FROM cus
LEFT OUTER JOIN invoice ON cus.cus_id = invoice.cus_id
WHERE cus.user_id='2'
GROUP BY cus.cus_id
To test this I have added some data to my database. The first customer has 2 invoices with a total sum of 100 (50+50).
The second customer has 3 invoices with a total sum of 30 (10+10+10).
But the SQL code dont shows me these results.
The response is for customer 1: total invoices = 1, total = 50
The response is for customer 1: total invoices = 0, total = (empty)
Does someone know what is wrong with my SQL statement?
The database type I am using is MySQL.
Here is a sample: http://sqlfiddle.com/#!9/a9f9f/1

Try grouping up your invoice count and sum as a subquery first, like:
SELECT cus.cus_id, cus.name_cus, inv.invoice_count, inv.invoice_total, cus.id
FROM cus
LEFT OUTER JOIN
(
SELECT inv.cus_id,
COUNT(inv.id) AS invoice_count,
CONCAT('€ ', ROUND(SUM(inv.total),2)) AS invoice_total
FROM invoice inv
GROUP BY inv.cus_id
) inv
ON cus.cus_id = inv.cus_id
WHERE cus.user_id='2'

If you're using SQL Server then your query should be like this --
SELECT C.cus_id
,C.name_cus
,Count(I.id) AS NumberOfInvoices
,IsNull(Sum(I.Price), 0) AS TotalPrice
FROM Customer C
LEFT JOIN Invoice I ON C.cus_id = I.cus_id
GROUP BY C.cus_id, C.name_cus
ORDER BY C.cus_id;

This is a simple sql Query as i understood your problem. I assumed CustomerID is in both tables. I think this Query will help you.
select i.CustomerID,i.CustomerName,COUNT(i.InvoiceID) as A, SUM(i.invoicetotal) as b
from Cus c,Invoice i
where i.CustomerID=c.CustomerID
group by i.CustomerID

Related

Inner Join for 3 tables with SUM of two columns in SQL Query?

I have the following three tables:
I have Following Query to Join Above 3 Tables
customer.customer_id,
customer.name,
SUM(sales.total),
sales.created_at,
SUM(sales_payments.amount)
FROM
sales INNER JOIN customer ON customer.customer_id = sales.customer_id
INNER JOIN sales_payments ON sales.customer_id = sales_payments.customer_id
WHERE sales.created_at ='2020-04-03'
GROUP By customer.name
Result for Above Query is given below
Sum of sales.total is double of the actual sum of sales.total column which has 2-row count, I need to have the actual SUM of that column, without doubling the SUM of those rows, Thank you, for your help in advance..
PROBLEM
The problem here is that there are consecutive inner joins and the number of rows getting fetched in the second inner join is not restricted. So, as we have not added a condition on sales_payment_id in the join between the sales and sales_payment tables, one row in sales table(for customer_id 2, in this case) would be mapped to 2 rows in the payment table. This causes the same values to be reconsidered.
In other words, the mapping for customer_id 2 between the 3 tables is 1:1:2 rather than 1:1:1.
SOLUTION
Solution 1 : As mentioned by Gordon, you could first aggregate the amount values of the sales_payments table and then aggregate the values in sales table.
Solution 2 : Alternatively (IMHO a better approach), you could add a foreign key between sales and sales_payment tables. For example, the sales_payment_id column of sales_payment table can be introduced in the sales table as well. This would facilitate the join between these tables and reduce additional overheads while querying data.
The query would then look like:
`SELECT c.customer_id,
c.name,
SUM(s.total),
s.created_at,
SUM(sp.amount)
FROM customer c
INNER JOIN sales s
ON c.customer_id = s.customer_id
INNER JOIN sales_payments sp
ON c.customer_id = sp.customer_id
AND s.sales_payments_id = sp.sales_payments_id
WHERE s.created_at ='2020-04-03'
GROUP BY c.customer_id,
c.name,
s.created_at ;`
Hope that helps!
You have multiple rows for sales_payments and sales per customer. You need to pre-aggregate to get the right value:
SELECT c.customer_id, c.name, s.created_at, s.total, sp.amount
FROM customer c JOIN
(SELECT s.customer_id, s.created_at, SUM(s.total) as total
FROM sales s
WHERE s.created_at ='2020-04-03'
GROUP BY s.customer_id, s.created_at
) s
ON c.customer_id = s.customer_id JOIN
(SELECT sp.customer_id, SUM(sp.amount) as amount
FROM sales_payments sp
GROUP BY sp.customer_id
) sp
ON s.customer_id = sp.customer_id

Need to know how to select customer names where their purchase price is greater than 100

i have a sql homework. i Have built a small database with 3 tables(in images).I need to select customer names that have purchased for more than 100 within last month.All purchases are separated.
I tried using using SUM
SELECT customer.CustomerName
FROM customer INNER JOIN
sales
ON customer.id=sales.CustomerId
HAVING SUM(sales.SalesPrice > 100)
In my database there are customers that the sum of Sales price is greteater than 0 but SQL return blank outputenter image description here
Try this:
SELECT customer.customerName FROM customer
INNER JOIN sales ON customer.id = sales.customerId
GROUP BY customerName
HAVING SUM(sales.SalesPrice) > 100;
The correct syntax looks like this:
SELECT c.CustomerName
FROM customer c INNER JOIN
sales s
ON c.id = s.CustomerId
GROUP BY c.id, c.CustomerName
HAVING SUM(s.SalesPrice) > 100;
I need to select customer names that have purchased for more than 100 within last month
SELECT C.CustomerName
FROM customer AS C INNER JOIN sales AS S ON C.id = S.CustomerId
WHERE S.SalesDate >= '20190701' AND S.SalesDate < '20190801' --within last month
GROUP BY C.CustomerName
HAVING SUM(S.SalesPrice) > 100 --Sum of purchases greater than 100
This sort of requires looking at the picture link, which should be included as part of the question, not as a link. For example, the link could expire or the link could be blocked by an organization's firewall.
The second part of this task needs me to write a query that return an item name that has the most transaction count. I need to know which ItemId.Sales has the most values. Currently I have this code
SELECT ItemName
FROM item
INNER JOIN sales ON item.id = sales.ItemID
but I need to know how to count those ItemID's and which ID has the biggest count

Counting amount of base records in (My)Sql 1-to-many relation

I have these two tables:
invoices (contains id field)
contracts (contains fk to invoice + 'code' field)
Let's say I have one record in the invoices table and two records in the contracts table. Both records in the contracts table point to the same invoice record.
Desire: I'd like to count the amount of invoices.
What I've got so far:
select
c.code, count(*)
from
invoices i
join
contracts c
on
c.invoice_id = i.id
group by
c.code
Although the count shows two instead of the desired 1. I understand that this is because of the join on the contract table, but not sure how to fix this.
Try with COUNT(DISTINCT i.id); it should count the different invoice id's in the resultset.
select
c.code, count(distinct i.id)
from
invoices i
join
contracts c
on
c.invoice_id = i.id
group by
c.code
You want the number of invoices?
select count(*)
from invoices i
You want invoices with contracts?
select count( distinct c.invoice_id)
from
contracts
Your code finds number of contracts per each invoice

A SQL query that does not work for getting number of orders in a table

This is a part of SQL coding project of database.
I need to design a single table to hold orders made by customers.
Assume that customers' details (e.g. names) are stored in another table.
Using the table that I designed for orders, and this assumed other table, write
a single SQL query that can give the number of orders for every customer, one line per customer.
The “Orders” table
Order_ID Order_NO Customer_ID
1 8088 3
2 9632 1
3 1272 4
4 6037 1
Assume that the customer names and other details (address, phone numbers, emails) are stored in the “Customers” table.
My SQL:
SELECT Customers.FirstName, Customers.FirstName, Orders.OrderNo
FROM Customers
FULL JOIN Orders
ON Customers.Customer_ID = Orders.Customer_ID
ORDER BY Customers.LastName
Are there something wring with it ?
Change the query to inner join
SELECT
Customers.FirstName
, Customers.FirstName
, Orders.OrderNo
FROM
Customers
INNER JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID
ORDER BY
Customers.LastName
Query for Ordercount for customer
SELECT
Customers.LastName
, COUNT(Orders.Order_Id)
FROM
Customers
INNER JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID
GROUP BY
Customers.LastName
ORDER BY
Customers.LastName
Full join
http://www.w3schools.com/sql/sql_join_full.asp
Inner join
http://www.w3schools.com/sql/sql_join_inner.asp
If you just want to COUNT the orders you can do this:
SELECT
Customers.FirstName,
(
SELECT
COUNT(*)
FROM
Orders
WHERE
Orders.Customer_ID=Customers.Customer_ID
) AS NbrOfOrders
FROM
Customers
References:
12.15.1. GROUP BY (Aggregate) Functions
Don't forget COUNT and GROUP BY.

Need help get following query

I have three tables customer, customer_account, account_transaction
Table structure is as follow -
Customer
Id,
Branch,
Name
..
customer_account
Id,
Cust_id,
Loanamout,
EMI
account_transaction
ID,
account_id,
amount,
date
I need to get branch wise details in form of count of Loan given, sum of loan given, and sum of emi received for a particular branch. below is my current query -
SELECT
count(s.id) as cntloan,
SUM(s.Loanamout)
(
SELECT SUM(amount)
FROM account_transaction i
WHERE s.id = i.account_id
) AS curbal
From
customer as c,
customer_account as s
where c.branch = 1 and s.cust_id = c.id
It is giving me desired result for count of loan and sum of loan given. but not giving the right sum of EMI paid by customers
Can anyone help me on this.
Thanks you very much
This SQL has aggregative functions such as count and sum, so without a group by, this would not work.
SELECT customer.id,
COUNT(customer_account.id) as cntloadn,
SUM(customer_account.loan) as loan,
SUM(account_transaction.amount)
FROM customer
JOIN customer_account ON customer_account.cust_id = customer.id
JOIN account_transaction ON account_transaction.account_id = customer_account.id
GROUP BY customer.id