SQL QUERY for sum loans per customer - sql

enter image description here
I need a query that returns all customers whose name contains the string "Will", and their associated total loan values.
Loan totals should be sorted from largest amount to smallest amount and the loans totals column should be called "TotalLoanValue".
Only one record per customer should be returned.
SELECT name, loan_amount
FROM customers, loans
WHERE name LIKE '%WILL%'
I have wrote that query, but I'm having a hard time to figure out how to sum all the loan values per customer

To say first things first:
If you want to ask further questions here, you should please read and follow this: How to create a good example instead of just adding a link.
Otherwise, you will be on risk that your questions will just be closed and you will never get an answer.
To answer your question:
We need to JOIN the two tables by their common column and then build the SUM of all loan amounts with a GROUP BY clause of the customer name.
I didn't follow your link because I wouldn't know if this is spam, so let's say the customer table has a column "id" and the loan table a column "customer_id".
Then your query will look like this:
SELECT c.name, SUM(l.loan_amount)
FROM customers c
JOIN loan l
ON c.id = l.customer_id
WHERE c.name LIKE '%will%'
GROUP BY c.name
ORDER BY SUM(l.loan_amount) DESC, c.name;
The ORDER BY clause makes sure to begin with the customer having the highest sum of loan amounts.
The "c.name" at the end of the ORDER BY clause could be removed if we don't care about the order if different customers have the same sum of loan amounts.
Otherwise, if we use the query as shown, the result will be sorted by the sum of loan amounts first and then with a second priority by the customer name, i.e. will sort customers having the identic sum of loan amounts by their name.
Try out with some sample data here: db<>fiddle

Related

SQL Databricks - Selecting the number of customers that have not bought anything from certain product categories

Do you know how I can select the number of customers that have not bought anything from specific product categories, for a 6 months period of time?
The result should look something like that:
table_example
I tried to full outer join the sales table, the product categories table and the customer ids table, then count the null values from the customer ids table. Returned no results.

How do I use array_agg with a condition?

I have a table with a list of potential customers, their activity, and their sales representative. Every customer can have up to 1 sales rep. I've built a summary table where I aggregate the customer activity, and group it by the sales rep, and filter by the customer creation date. This is NOT a cohort (the customers do not all correspond to the scheduled_flights, but rather this is a snapshot of activity for a given period of time) It looks something like this:
Now, in addition to the total number of customers, I'd also like to output an array of those actual customers. The customers field is currently calculated by performing sum(is_customer) as customers and then grouping by the sales rep. To build the array, I've tried to do array_agg(customer_name) which outputs the list of all customer names -- I just need the list of names who also satisfy the condition that is_customer = 1, but I can't use that as a where clause since it would filter out other activity, like scheduled and completed flights for customers that were not new.
This should probably work:
array_agg(case when is_customer = 1 then customer_name end) within group (order by customer_name)
Snowflake should ignore NULL values in the aggregation.

SUM and JOIN clause in sql

There are 3 tables with respective columns :
wc_dept : dept_id,dept_name
wc_doctor : dept_id,doc_id,doc_name,consult_fee
wc_patient: doc_id,consult_id,patient_name
For the following queries I am getting different results :
Query 1 :
select dept_name,sum(consult_fee)
from wc_doctor do,wc_dept dp,wc_patient p
where
do.dept_cd=dp.dept_cd
AND
do.doc_id=p.doc_id
group by dept_name;
The output for the above query is a very large amount of money for every department compared to the actual amount i.e, sum of consultation fee in each department.
Query 2 :
select dept_name,sum(consult_fee)
from wc_doctor do,wc_dept dp
where
do.dept_cd=dp.dept_cd
group by dept_name;
The output of the Query 2 gives the exact sum of consultation fee for each department.
Why is the difference between query1 and query2 ? how is consult_id column behaving in query1?
Well query1 and query2 are different.
In Second Query you are SUM how much charge each doctor in the department for check a single patient.
But in the first one you are SUM how much all the patient are pay to the department
You need to understand that the join happens before aggregation, and that joins will duplicate values in the parent table for each row in the joined child table.
consult_fee is a column in wc_doctor. You want to sum that once per row in wc_doctor. When you join to wc_patient, theconsult_fee` for each doctor is repeated, per patient, and the sum will add up over all that duplication.
If you really want to include the doctor's consult fee in a query that includes patients, you need to aggregate it separately in a subquery, then join that result against patients.

Multiple records joined Access SQL

I'm not sure if what I want to do is possible but if it is possible, it's probably a really easy solution that I just can't figure out. Once things get to a certain complexity though, my head starts spinning. Please forgive my ignorance.
I have a database running in MS Access 2007 for a school which has a plethora of tables joined to each other. I'm trying to create a query in which I get information from several tables. I'm looking up sales and payment information for different customers, pulling info from several different linked tables. Each sale is broken down into one of 4 categories, Course Fee, Registration Fee, Book Fee and Others. Because each customer will have multiple purchases, each one is a separate entry in the Sales table. The payment information is also in its own table.
My SQL currently looks like this:
SELECT StudentContracts.CustomerID, (Customers.CFirstName & " " & Customers.CLastName) AS Name, Customers.Nationality, Courses.CourseTitle, (StudentContracts.ClassesBought + StudentContracts.GiftClasses) AS Weeks, StudentContracts.StartDate, Sales.SaleAmount, SaleType.SaleType, Sales.DueDate, Payments.PaymentAmount
FROM (
(
(Customers INNER JOIN StudentContracts ON Customers.CustomerID = StudentContracts.CustomerID)
INNER JOIN Payments ON Customers.CustomerID = Payments.CustomerID)
INNER JOIN
(SaleType INNER JOIN Sales ON SaleType.SalesForID = Sales.SalesForID)
ON Customers.CustomerID = Sales.CustomerID)
INNER JOIN
(
(Courses INNER JOIN Classes ON Courses.CourseID = Classes.CourseID)
INNER JOIN StudentsClasses ON Classes.ClassID = StudentsClasses.ClassID)
ON Customers.CustomerID = StudentsClasses.CustomerID;
This works and brings up the information I need. However, I am getting one record for each sale as in:
CustomerID Name ... SaleAmount SaleType PaymentAmount
1 Bob $600 Course $1000
1 Bob $300 RgnFee $1000
1 Bob $100 Book $1000
What I need is one line for each customer but each sale type in it's own column in the row with the sale amount listed in its value field. As so:
CustomerID Name ... Course RgnFee Book Others PaymentAmount
1 Bob $600 $300 $100 $1000
Can anyone help and possibly explain what I should/need to be doing?
Thanks in advance!
You can create a cross tab from the query you have already created. Add the query to the Query Design Grid, choose Crosstab from query types, and select a Row or rows, Column and Value.
Say:
TRANSFORM Sum(t.SaleAmount) AS SumOfSaleAmount
SELECT t.ID, t.Name, Sum(t.SaleAmount) AS Total
FROM TableQuery t
GROUP BY t.ID, t.Name
PIVOT t.SaleType
If you want a certain order, you can edit the property sheet to include column headings, or you can add an In statement to the SQL. Note that if you add column headings, a column will be included for each column, whether or not data is available, and more importantly, a column will not be included that has data, if it is not listed.
TRANSFORM Sum(t.SaleAmount) AS SumOfSaleAmount
SELECT t.ID, t.Name, Sum(t.SaleAmount) AS Total
FROM TableQuery t
GROUP BY t.ID, t.Name
PIVOT t.SaleType In ("Course","RgnFee","Book","Others");

Select records for MySQL only once based on a column value

I have a table that stores transaction information. Each transaction is has a unique (auto incremented) id column, a column with the customer's id number, a column called bill_paid which indicates if the transaction has been paid for by the customer with a yes or no, and a few other columns which hold other information not relevant to my question.
I want to select all customer ids from the transaction table for which the bill has not been paid, but if the customer has had multiple transactions where the bill has not been paid I DO NOT want to select them more than once. This way I can generate that customer one bill with all the transactions they owe for instead of a separate bill for each transaction. How would I build a query that did that for me?
Returns exactly one customer_id for each customer with bill_paid equal to 'no':
SELECT
t.customer_id
FROM
transactions t
WHERE
t.bill_paid = 'no'
GROUP BY
t.customer_id
Edit:
GROUP BY summarises your resultset.
Caveat: Every column selected must be either 'grouped by' or aggregated in some fashion. As shown by nikic you could use SUM to get the total amount owed, e.g.:
SELECT
t.customer_id
, SUM(t.amount) AS TOTAL_OWED
FROM
transactions AS t
WHERE
t.bill_paid = 'no'
GROUP BY
t.customer_id
t is simply an alias.
So instead of typing transactions everywhere you can now simply type t. The alias is not necessary here since you query only one table, but I find them invaluable for larger queries. You can optionally type AS to make it more clear that you're using an alias.
You might try the Group By operator, eg group by the customer.
SELECT customer, SUM(toPay) FROM .. GROUP BY customer