SQL JOIN AND SUB QUERY - sql

below are two tables customer information and second customer with their loan and repayment I want to join these two tables and retrieve the expected result in the picture, please note that in the second table one customer can have more than one loan and he/she can repay it in several installments that in the second table that it saved in many rows, I am expecting to join the two tables and retrieve clients who are still owed from the company.
I found the expected result as a good solution for this purpose but could not retrieve the expected result.
and if you have a good solution for my purpose rather than expected result please share.
example:-
I tried below query but it does not work, because the client id number 1 disbursed three times loan when it shows the tree times purpose it shows that total of the loan three times too
SELECT DISTINCT
CUSTOMER_AIB_INFO_TABLE.ID,
CUSTOMER_AIB_INFO_TABLE.NAME,
(
SELECT SUM (CUSTOMER_AIB_LOAN_TABLE.LOAN) AS "Total Loan"
FROM CUSTOMER_AIB_LOAN_TABLE
WHERE CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID
) AS "Loan",
(
SELECT SUM (CUSTOMER_AIB_LOAN_TABLE.REPAYMENT) FROM CUSTOMER_AIB_LOAN_TABLE
WHERE CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID
) AS Repayment ,
CUSTOMER_AIB_LOAN_TABLE.PURPOSE
FROM CUSTOMER_AIB_INFO_TABLE
INNER JOIN CUSTOMER_AIB_LOAN_TABLE
ON CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID

Instead of Subquery you could use a inner join on select table group by id
SELECT DISTINCT
CUSTOMER_AIB_INFO_TABLE.ID,
CUSTOMER_AIB_INFO_TABLE.NAME,
T.Total_Loan AS "Loan",
T.Total_Rep AS Repayment,
CUSTOMER_AIB_LOAN_TABLE.PURPOSE
FROM CUSTOMER_AIB_INFO_TABLE
INNER JOIN (
SELECT CUSTOMER_AIB_LOAN_TABLE.FK_ID as FK_ID,
SUM (CUSTOMER_AIB_LOAN_TABLE.LOAN) AS Total_Loan
, SUM (CUSTOMER_AIB_LOAN_TABLE.REPAYMENT) AS Total_Rep
FROM CUSTOMER_AIB_LOAN_TABLE
GROUP BY CUSTOMER_AIB_LOAN_TABLE.ID
) T on t.FK_ID = CUSTOMER_AIB_INFO_TABLE.ID

Related

SQL - Create complete matrix with all variables even if null

please provide some assistance/guidance to solve the following:
I have 1 main table which indicates sales volumes by sales person per different product type.
Where a salesperson did not sell a particular product on a particular day, there is no record.
The intention is to create null value records for salesmen that did not sell a product on a specific day. The query must be dynamic as there are many more salesmen with sales over many days.
Thanks in advance
Just generate records for all sales persons, days, and products using cross join and then bring in the existing data:
select p.salesperson, d.salesdate, st.salestype,
coalesce(t.sales_volume, 0)
from (select distinct salesperson from t) p cross join
(select distinct salesdate from t) d cross join
(select distinct salestype from t) st left join
t
on t.salesperson = p.salesperson and
t.salesdate = d.salesdate and
t.salestype = st.salestype;
Note: You may have other tables that have lists of sales people, dates, and types -- and those can be used instead of the select distinct queries.

How do you conditionally join a string from Table B to Table A, using an aggregate function on Table B date?

I am attempting to do a conditional join from Tickets to Sales. Tickets:Sales is 1:M. My goal is to provide a list of tickets, and the Sales Channel of the first transaction:
Ex:
select r.ticket_id, s.channel, min(s.transaction_date)
from reservations r
join sales s on r.ticket_id = s.ticket_id
where r.order_id = '0151841621'
group by select r.ticket_id, s.channel;
If I have Reservation ID 123 and it has two records in the Sales table, an online sale and a retail refund, I get the following result
r.ticket_id, s.channel, transaction_date
123, Ecommerce, 2019-07-01:00:00:00
123, Retail, 2019-07-02:00:00:00
I'm looking for a way to combine this into a single table with 1 reservation record, based on the min(transaction_date).
i.e.
123, Ecommerce
Pusedo code
select r.ticket_id, [s.channel where min(transaction_date)]
i.e. select the Channel with the first transaction date.
I've been searching for "conditional select / conditional join" without much luck.
I think you want distinct on:
select distinct on (r.ticket_id) r.ticket_id, s.channel, s.transaction_date
from reservations r join
sales s
on r.ticket_id = s.ticket_id
where r.order_id = '0151841621'
order by r.ticket_id, s.transaction_date;

Total amount of financing already provided to each customer

I have three separate tables:
SystemA_Cash
SystemA_Loans
SystemB_CarLoans
Each table has Cash_AdvanceID field, Customer, & Funded Amount.
I need to total the amount funded for each customer.
Each customer can be present in any of the tables too.
So far I did
SELECT SystemA_CashAdvances.CashAdvanceID, SystemA_CashAdvances.Customer,
SystemA_CashAdvances.Funded_Amount
FROM
SystemA_CashAdvances
INNER JOIN
SystemA_Loans ON SystemA_Loans.CashAdvanceID = SystemA_CashAdvances.Cash_AdvanceID
INNER JOIN
SytemB_CarLoans ON SystemA_CashAdvances.Cash_AdvanceID = SystemB_CarLoans.CashAdvanceID;
It doesn't seem to return one table with the customers and the total amount each was funded.
You can use UNION and GROUP BY for this, like:
SELECT Cash_AdvanceID,
Customer,
SUM(Funded_Amount) AS "Total_Funded_Amount"
FROM (
SELECT Cash_AdvanceID,
Customer,
Funded_Amount
FROM SystemA_CashAdvances
UNION
SELECT Cash_AdvanceID,
Customer,
Funded_Amount
FROM SystemA_Loans
UNION
SELECT Cash_AdvanceID,
Customer,
Funded_Amount
FROM SytemB_CarLoans
)
GROUP BY Cash_AdvanceID,
Customer;
To do this with JOIN will be hard, as MS Access does not support a full outer join, as other database engines do. The closest is a one-sided outer join, as follows:
SELECT a.Cash_AdvanceID,
a.Customer,
a.Funded_Amount + Nz(l.Funded_Amount)
+ Nz(c.Funded_Amount) AS "Total_Funded_Amount"
FROM (SystemA_CashAdvances AS a
LEFT JOIN SystemA_Loans AS l
ON a.Cash_AdvanceID = l.Cash_AdvanceID)
LEFT JOIN SytemB_CarLoans AS c
ON a.Cash_AdvanceID = c.Cash_AdvanceID;
The above will work for customers that appear at least in the table SystemA_CashAdvances. If they only appear in another table, they will be excluded from the result. To get those in as well, you would need to use UNION again, which brings us back to the first solution above.

sql sum from two tables

I've got two separate tables in sqlite called invoices and purchases and I am using the query below to retrieve the sum of all the invoices and purchases that related to project 7. The thing is the invoices have three records and the value returned in sql is correct, however the purchase equivalent is wrong as there is only one record, but the returned value is multiplied by three.
SELECT sum(invoice.invoice_net) As Sales, sum(purchase.total_order) As Purchases
FROM invoice
LEFT JOIN purchase
ON purchase.projectID=invoice.projectID
WHERE invoice.projectID=7
How can I join these two statements so I get the data returned correctly. I know individually they work fine. I've tried Union, but that puts the data into one column.
SELECT sum(invoice.invoice_net) As Sales
FROM invoice
WHERE projectID=7
SELECT sum(purchase.order_total) As Purchases
FROM purchase
WHERE projectID=7
One option is to sum the results using subqueries and then perform the outer join:
SELECT invoice.Sales, purchase.Purchases
FROM (
SELECT sum(invoice.invoice_net) As Sales, projectID
FROM invoice
GROUP BY projectID
) invoice LEFT JOIN (
SELECT sum(total_order) As Purchases, projectID
FROM purchase
GROUP BY projectID
) purchase ON purchase.projectID=invoice.projectID
WHERE invoice.projectID=7
Another option would be to use a correlated subquery:
SELECT sum(i.invoice_net) As Sales,
(SELECT sum(p.total_order)
FROM purchase p
WHERE p.projectID = i.projectID) As Purchases
FROM invoice i
WHERE i.projectID=7

SQL: Join 2 tables and return multiple rows from second table based on key of first table

I have one table 'Customers', with a key of customerid.
There is another table PaymentTotals which also has a customerid column. This table stores amounts paid by a customer (PaymentAmount) in a given week (weeknumber field). This implies that in the PaymentTotals table there may be several rows for any one customerid, the difference being the weeknumber for any of these rows.
I am trying to build a query in MSSQL that joins the two tables and will return for a given customerid the PaymentAmount for each different weeknumber.
It is not clear to me how to build this query. Any advice? Thanks.
SELECT *
FROM Customers C INNER JOIN PaymentTotals PT
ON C.customerid = PT.customerid
If you have multiple Payments made by one customer in a given week and want to get total by week you could do something like ....
SELECT C.customerid
,PT.WeekNumber
,SUM(PT.Payment_Column) AS TotalPayment
FROM Customers C INNER JOIN PaymentTotals PT
ON C.customerid = PT.customerid
GROUP BY C.customerid, PT.WeekNumber