SQL JOIN TWO TABLES WITH GROUP BY - sql

I am new to the world of databases etc. A developer who made my shop's POS took a large sum of money and would no longer answer me. I need to report my receivables as end end of the quarter. Please help with this query in access. I tried left join and it works fine when I join only the purchases, but not purchases and payments.
TABLES:
CUSTOMERSTABLE:
CUSTOMERID**********NAME
PURCHASESTABLE:
SALEID**********CUSTOMERID**********AMOUN******TDATE
PAYMENTSTABLE:
PAYMENTSID**********customerid*********amount******TDATE
The result should show all the customerids (with available transations or not), the total amount of purchases for each, the total amount of payments for each, the outstanding amount (net of the two), it should only consider transactions before a given TDATE

SELECT cust.customerid, Sum(purch.Amount_charged) AS totalPurchases, Sum(pay.Payment_Made) AS SumOfPayment_Made
FROM (cust INNER JOIN pay ON cust.customerid = pay.Account_Id) INNER JOIN purch ON cust.customerid = purch.Account_Id
WHERE ((([purch].[TDATE]) Between '4/6/2015' And '5/18/2015'))
GROUP BY cust.customerid;

Related

3 Tables into dropdown list

I have 3 tables, Clients, Products, Transactions.
When we enter a product, it is given a PID (product id) and a CID (client ID), which relate to the Clients and Transaction tables. The transaction table has a CID and Quantity.
I am trying to list all unique products and quantities, some clients have 2 listings of the same product, so if 1 is 10 units and the other is 20, then that client has 30 of product a.
The transactions table lists all sales, which are subtracted from the total.
I need the query to show the product name, client name, quantity available.
Here is the code I have so far, apologies for the mess and thanks much for any help.
This is an Access database.
SELECT Min(Products.PID) exPID,
Min(Products.[Product Name]) AS exProdName,
Min(Products.[Seller Asking]) AS exAsking,
Min(Products.CID) AS exClientID,
Min(Transactions.[CID Seller]) AS exSellerID,
Sum(Products.Quantity - ((SELECT Transactions.[No Units], Clients.Name,
Transactions.[CID Seller], Products.CID
FROM Transactions, Clients, Products
WHERE Transactions[CID Seller]=Products.CID)
) AS exSumofTrans),
Min(Clients.Name) AS exClientName,
Min(Transactions.[CID Seller]) AS exSeller
FROM Transactions, Clients, Products
WHERE (((Transactions.[CID Seller])=[Products].[CID]
AND (Products.[PID])=([Transactions].[PID])));
First issue here is an error on the inner select.
The error says:
'Syntax error in query expression (Sum(Products.Quantity-((Select Transactions.[No Units], Clients.Name, Transactions.[CID Seller], Products.CID
FROM Transactions, Clients, Products
Where Transactions[CID Seller]=Products.CID)) as exSumofTrans)'.
I had to do some guessing based on what it looks like you are trying to do and I have no way of testing it so it may need further tweaking but this will get you on the right path:
SELECT Products.PID AS exPID,
FIRST(Products.[Product Name]) AS exProdName,
FIRST(Products.[Seller Asking]) AS exAsking,
FIRST(Products.CID) AS exClientID,
SUM(Products.Quantity)-FIRST(T.exNoUnits) AS exSumofTrans,
T.exSellerID,
FIRST(Clients.Name) AS exClientName
FROM (Products
INNER JOIN (SELECT [CID Seller] AS exSellerID, PID, SUM([No Units]) AS exNoUnits
FROM Transactions GROUP BY [CID Seller], PID) AS T
ON T.PID=Products.PID)
INNER JOIN Clients ON T.exSellerID=Clients.CID
GROUP BY Products.PID, T.exSellerID

Access 2013 SQL, three tables, two using sum wrong results

Can someone please help me with this issue? I've scoured the Internet looking at dozens of examples, but i just can't find a solution that works.
I am using Access 2013. The problem is that I am trying to make a query that will highlight all part numbers from a supplier that either has customer back orders and/or overdue deliveries.
I am using three tables:
tbl_Inventory_Master which I require the part number, on hand stock value, and the supplier code.
For any back orders I need to join the tbl_Customer_Back_Order table as I need the count of back order lines and the sum of the back order quantity.
If the supplier has a late delivery, then I need to add the tbl_On_Order table showing the count of overdue deliveries and the sum of the overdue quantities.
The query is retrieving the data but the returned quantities are double what they should be.
SELECT
I.Inventory_Part_Num, I.Description, I.On_Hand_Stock,
COUNT (B.Part_Number) AS Back_Order_Count, SUM(B.Back_Order_Qty) as BO_Qty,
COUNT(O.Part_Number) AS Late_Deliveries_Count, SUM(O.Order_Qty) AS Late_Qty
FROM (tbl_Inventory_Master AS I
LEFT OUTER JOIN tbl_Customer_Back_Order AS B
ON I.Inventory_Part_Num = B.Part_Number)
LEFT OUTER tbl_On_Order AS O
ON I.Inventory_Part_Num = O.Part_Number
WHERE
I.Customer_Code = '274' AND
O.Due_Date < [ENTER TODAYS DATE IN FORMAT DD/MM/YYYY]
GROUP BY I.Inventory_Part_Num, I.Description, I.On_Hand_Stock
For example, for the part number 2022940 I should have 10 back order lines and an overdue quantity of 43. Instead, the query is returning 20 back order lines and an overdue quantity sum of 86.
From the on order table I have three orders totaling 144 pieces, instead the query is returning 960.
Can someone please advise, as this is driving me crazy?
You are joining along unrelated dimensions, so you need to aggregate before joining:
SELECT I.Inventory_Part_Num, I.Description, I.On_Hand_Stock,
B.Back_Order_Count, B.BO_Qty,
O.Late_Deliveries_Count, O.Late_Qty
FROM (tbl_Inventory_Master AS I LEFT OUTER JOIN
(SELECT B.Part_Number, COUNT(*) as Back_Order_Count,
SUM(B.Back_Order_Qty) as BO_Qty
FROM tbl_Customer_Back_Order AS B
GROUP BY B.Part_Number
) as B
ON I.Inventory_Part_Num = B.Part_Number
) LEFT JOIN
(SELECT O.Part_Number, COUNT(O.Part_Number) AS Late_Deliveries_Count,
SUM(O.Order_Qty) AS Late_Qty
FROM tbl_On_Order AS O
WHERE O.Due_Date < [ENTER TODAYS DATE IN FORMAT DD/MM/YYYY]
GROUP BY O.Part_Number
) as O
ON I.Inventory_Part_Num = O.Part_Number
WHERE I.Customer_Code = '274';
Notice the outer aggregation is no longer needed.

SQL Query Daily Sales Per Month of a specific product

I've got a query which gets the lists of customers who've made a purchase of the product for the current day
select Customer.customerName, sum(InvoiceDetail.itemPrice * InvoiceDetail.itemQuantity) as dailyPurchase from Invoice
inner join InvoiceDetail on Invoice.invoiceID = InvoiceDetail.invoiceID
inner join Customer on Invoice.customerID = Customer.customerID
inner join Item on InvoiceDetail.itemID = Item.itemID
inner join Branch on Branch.branchID = Invoice.branchID
inner join Region on Region.regionID = Branch.regionID
where
Invoice.inactive = 0 and InvoiceDetail.inactive = 0
and Item.itemTypeID = 3
and Region.regionCode = 'CR'
and cast(Invoice.invoiceDate as date) = convert(date, '01/08/2016', 103)
group by Customer.customerName
What I need is a table with a list of all the dates in the current month, listing ALL customers who have at least purchased the product ONCE. It should resemble something similar to this image here.
Any help on how to get started or a general idea of how to get the desired result, is much appreciated. Thanks!
Sample Data from Results:
customerName dailyPurchase
AGH COMMUNICATIONS 450.00
ARIEL AMARCORD SHOP 285.00
AKN COMMUNICATION 300.00
AWSDAC TELECOMMUNICATION 2850.00
BARLEY MOBILE & SERVICES 285.00
Table Structure - I'm sorry, I don't know an easier way to copy this.
First get the customers who have purchased the product atleast once this month alongwith date.
Then use pivot to get the result in the form that you want (as seen in image). Search stackoverflow for pivot in sql server, you will get good info.
Give some information about the table structure and sample data and I might be able to help you with the query to get the results.

SQL query to report on what invoices have not been paid, ordered by invoice number

new to SQL and only been doing it for a week and a half. So I apologise now for the question being simple or appearing to be stupid.
I want to present a report on invoices that have not been paid by a given date, ordered by invoice number.
This is how I have displayed, the paid invoices but without the given date.. How do I display, the invoices that have not been paid by say 31-MAR-14.
SELECT INVOICE.INVOICE_NUMBER, INVOICE.INVOICE_DATE, PAYMENT.PAYMENT_NO, PAYMENT.INVOICE_NUMBER
FROM INVOICE, PAYMENT
WHERE INVOICE.INVOICE_NUMBER = PAYMENT.INVOICE_NUMBER
ORDER BY INVOICE.INVOICE_NUMBER;
SELECT PAYMENT.PAYMENT_NO
FROM INVOICE, PAYMENT
WHERE INVOICE.INVOICE_NUMBER = PAYMENT.INVOICE_NUMBER
AND INVOICE.INVOICE_DATE = 'AAAAMMJJ'
ORDER BY INVOICE.INVOICE_NUMBER;
Try something like this.
I have question. How do you say the invoice are not paid ?
You need to join the two tables together with a LEFT JOIN, then look to see where the payment date is > 31-MAR-14. Try something like this:
SELECT INVOICE.INVOICE_NUMBER, INVOICE.INVOICE_DATE, PAYMENT.PAYMENT_NO, PAYMENT.INVOICE_NUMBER
FROM INVOICE
LEFT JOIN PAYMENT ON INVOICE.INVOICE_NUMBER = PAYMENT.INVOICE_NUMBER
WHERE PAYMENT.Date_of_payment > '3/31/2014'
ORDER BY INVOICE.INVOICE_NUMBER;
This looks for all payments that were made after 3/31/2014. You may need to add another condition, that limits what invoices you're looking for.
To check payments that have not been made, look where any field in the PAYMENT table is null. SQL like this:
SELECT INVOICE.INVOICE_NUMBER, INVOICE.INVOICE_DATE, PAYMENT.PAYMENT_NO, PAYMENT.INVOICE_NUMBER
FROM INVOICE
LEFT JOIN PAYMENT ON INVOICE.INVOICE_NUMBER = PAYMENT.INVOICE_NUMBER
WHERE INVOICE.INVOICE_DATE = '3/31/2014'
AND PAYMENT.PAYMENT_NO IS NULL
ORDER BY INVOICE.INVOICE_NUMBER;
LEFT JOIN in this case will always return values for the INVOICE table, but may return NULL values in place of the PAYMENT if a payment has not been entered yet. Checking AND PAYMENT.PAYMENT_NO IS NULL will tell you that a payment has not been made yet.

Several inner joins producing too many rows

I'm working on a field trip request software for school districts.
Each field trip has an account attached to it that will be billed. It will also have one or more driver/vehicle combinations and mileage and driver rates associated with each driver/vehicle combination.
I'm working on an accounting report that will show, by account, a count of the trips that are assigned to that account, the total number of miles driven on that account times a certain charge basis, and a total number of hours each driver has driven on that trip multiplied by their payrate.
I have a field trip (tripid=1) with two vehicles and two drivers and I expect two rows of output. However, I am getting 4 rows; Two rows for vehicle 81 and two rows for vehicle 56. Is there something in my joins that's causing too many rows to be outputted?
What's weird is Mister Driver is on both vehicles in the output of my query and so is Generic Person.
select distinct
tdv.tripid as tripid,
ta.name as account,
cb.chargebasisname as trip_type,
cb.defaultdistancerate as distance_rate,
(tc.odometerreturn-tc.odometerstart) as total_miles,
datediff(hour, tc.actualoriginstarttime,tc.actualoriginreturntime) as total_hours,
v.vehicle,
pr.hourlyrate as driver_rate,
e.firstname+' '+e.lastname as driver
from trip_tripdrivervehicle tdv
join trip_tripinformation ti
on ti.recordid = tdv.tripid
join trip_transportationaccounts ta
on ta.recordid = ti.accountid
join trip_invoicechargebasis cb
on cb.recordid = ta.defaultchargebasisid
join trip_tripcompletion tc
on tc.tripid = ti.recordid
join vehicles v
on v.recordid = tc.vehicleid
join trip_employeejobcategorypayrate pr
on pr.employeeid = tdv.driverid
join employees e
on e.recordid = tdv.driverid
where ti.triprequeststatusid = 7 and ti.recordid = 1
Here is my output:
https://lh6.googleusercontent.com/_Bbr20KcwLyw/TX5cwDhr7BI/AAAAAAAAbYE/qCfQtk6Xmeg/s800/sql_results.jpg
Looks like you also have two matches for the JOIN with table trip_tripcompletion - one that gives rows with total miles of 10 and another that gives rows with total miles of 50.
So each driver shows up with each total_miles option.
The JOIN condition for this table may need to be changed, or you can use GROUP BY along with MAX/MIN to show only the shortest/longest trip (depending on the need).