Calculate differences between two columns of two different tables - sql

I want to calculate the difference between purchase order amount and purchase invoice amount. But I am not able to fetch the purchase invoice amount i.e. "pi.grand_total" and hence also not able to fetch the difference of "(pi.grand_total - po.grand_total)" . Please help.Below is my query.
PO = Purchase Order
PI = Purchase Invoice
SELECT DISTINCT
po.name AS "PO #:Link/Purchase Order:120",
po.supplier AS "Supplier:Link/Supplier:120",
po.Company AS "Company:Data:120",
po.currency AS "Currency:Link/Currency:120",
po.base_grand_total AS "Grand Total:Currency:120",
po.status AS "Status:Data:120",
po.per_received AS "Per Received:Data:120",
CEILING(po.per_billed) AS "Per Billed:Data:120",
po.delivery_date AS "Delivery Date:Date:120",
pi.grand_total AS "Final PI Total:120",
(pi.grand_total - po.grand_total) AS "Amount Difference:120"
FROM
"tabPurchase Order" as po
LEFT JOIN "tabPurchase Invoice" as pi ON po.name = pi.parent
WHERE
po.per_received = 100
AND
CEILING(po.per_billed) < 100
ORDER BY po.delivery_date ASC

You are using LEFT JOIN. This means when your second table has no data which matches with your first table you will receive no data from second table but nonetheless your first table will return all of its data.
You probably should check your join condition. If you wanted to join these two tables the way you want then use NVL Function for pi.grand_total column. Because it is on the left join it could have a NULL value thus NULL minus po.grand_total will give you NULL. NVL function turns NULL values into intended values like NVL(pi.grand_total,0)
A good example how joins work

Related

Expand Join to not limit data

I have a weird question - I understand that Joins return matching data based on the 'ON' stipulation, however the problem I am facing is I need the Business date back for both tables but at the same time i need to join on the date in order to get the totals correct
See below code:
Select
o.Resort,
o.Business_Date,
Occupied,
Comps,
House,
ADR,
Room_Revenue,
Occupied-(Comps+House) AS DandT,
Coalesce(gd.Projected_Occ1,0) AS Projected_Occ1,
Occupied-(Comps+House)+Coalesce(gd.Projected_Occ1,0) as Total
from Occupancy o
left join Group_Details_HF gd
on o.Business_Date = gd.Business_Date
and o.Resort = gd.resort
UNION ALL
select
o.Resort,
o.Business_Date,
Occupied,
Comps,
House,
ADR,
Room_Revenue,
Occupied-(Comps+House) AS DandT,
Coalesce(gd.Projected_Occ1,0) AS Projected_Occ1,
Coalesce(Occupied-(Comps+House),0)+Coalesce(gd.Projected_Occ1,0) as Total
from Occupancy_Forecast o
FULL OUTER JOIN Group_Details_HF gd
on o.Business_Date = gd.Business_Date
and o.Resort = gd.resort
Currently, this gives me the desired results from the Occupancy and Occupancy forecast table however when the business date does not exist in the occupancy forecast table it ignores the group_details table, I need the results to combine the dates when they exist in both or give the unique results for each when there is no match
I have decided to create another pivot table storing the details from Group_Details_HF and then Union together the two tables which has given me the desired result rather than fiddling with the join :)

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 Table Joining issue

I have a two tables: "invoice" as I and "Accounts Receivable" as AR.
AR table includes invoice issued (with id 0) and cash received (with id 4), while I table includes invoice amount column and adjustment column.
Apart from regular invoices and adjustments there are cases where adjustments were made to invoice and net affect is 0.00 on AR table. Plus sometimes, invoices are created and written off at invoice table before posting, so AR will have 0.00 amount in AR but I table has $100 in amount and -$100 in adjustment.
I am trying to create a query where it gives me invoice issued and cash received side by side and also create a new column that includes adjustment made for invoices with 0.00 balance in AR. Columns that might help:
AR.ID = unique ID
AR.ARinvnumber= Invoice number from Invoice table
Ar.Type= 0=invoice, 1 = payment received
Ar.Amount= ARamount saved from invoice
I.Id= unique ID
Invoice number = number of invoice
Invamount= Actual invoice amount
Inv Adjustment= Adjustment applied on invoice
Any idea how I can achieve that? I am able to match I and AR table and cash and AR from AR table
Select *
From (select ar.customerId, ar.customername,ar.invnumber ar.amount, i.invamout, i.invadjustment from Ar join I on ar.arinvnumber=i.invoicenumber where ar.artype=1) inv
join
select (select ar.customerId, ar.customername, ar.invnumber ar.amount, i.invamout, i.invadjustment from Ar join I on ar.arinvnumber=i.invoicenumber where ar.artype=1) cash
on inv.invnumber=cash.invnumber and inv.customerid=cash.customerid
after getting this, how can I include those invoices for whom adjustment were made but there was no AR because adjustment equals invoice amount.
Answer:
The following answer worked for me. Basically I wanted to include all the adjustments from invoice table including those ones which are not populated in AR table because the adjustments were made to clear client’s balance related to the work done after final invoice was issues. I used following query
Select *
From (select AR.ARInvnum as ARInvnum, AR.Arclientnumber as Aclient, sum(AR.Amount), I.Invoicenumber, sum(distinct(I.IAmount)), sum(I.IAdjust)
From AR.ARInvnum=I.Invoicenumber
Where ar.artype=0
Group by AR.ARInvnum, I.Invoicenumber, AR.Arclientnumber)AInvoice
Left join
(select AR.ARInvnum as PARInvnum, AR.Arclientnumber as PClient, sum(AR.Amount), I.Invoicenumber, sum (I.IAmount), sum(I.IAdjust)
From AR.ARInvnum=I.Invoicenumber
Where ar.artype=4
Group by AR.ARInvnum, I.Invoicenumber, AR.ARclientnumber)PInvoice
on
AInvoice.ARInvnum=PInvoice.PARInvnum
and
AInvoice.Aclient=PInvoice.PClient
Keep in Mind the Distinct clause in the first portion of the subquery removes any duplicates as well as sum them, so it will look like one summary related to particular invoice number. first portion of the subquery is summarizing based on the invoice issues and the adjustments related to the client. and second part is matching all payments received. I hope, this helps.
You need to include a limiting clause, also known as a where clause. MSDN documentation on select lays out the syntax as follows:
SELECT select_list [ INTO new_table ]
[ FROM table_source ] [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
Be aware, you will not need every expression to create a valid select statement. Also you do not need to join the same query to itself. Why not simplify by running the query by itself?
select
ar.customerId, ar.customername, ar.invnumber,
ar.amount, i.invamout, i.invadjustment
from Ar
join I on ar.arinvnumber=i.invoicenumber
where ar.artype=1
But your questions asks how to limit the results to only
those invoices for whom adjustment were made but there was no [account receivable]
Update your where clause to something like
where ar.artype=1 and i.adjustment is not null and i.adjustment = i.invamount
This will limit the results returned by the select statement to only those records that meet all three of the following criteria:
artype is equal to 1
adjustment is not null
adjustment is equal to invamount
If that result set is too narrow, tweak your where clause. I find it helpful to identify a single record that looks like other records I would like to find. Use that records unique identifier as a test for whether or not your query is working like you expect.

SQL query date column sorting issue

I am writing a SQL query which will return data of customer bills payments.
We have these payments in two different tables, one is "Bills" and other is "receipts". When my query data it shows that "receipts data" (from receipts table) in ascending order. I have two more date columns to show in result set which are "bill month" and "due date" (from bills table). When I try to apply order by on any of these mentioned columns it shows wrong data. Please help.
My query is attached below. thank you.
select distinct
bil.bill_id as Bill#, --(bill), this table has bill month and due date column
rec.receiptid as IDs, --(receipts),this table has receipt payment date,amount
sp.spaceno as spaceno,-- (space), this table has property names
lo.description as locaiton,-- (location),this table has details of property
one.name as owner_name,-- (owner), this table has owners information
bt.billtype as Particular,--(billtype),where bill types are saved
rec.rdate as Date,-- this column of receipt table showing wrong date data
dc.dr as opening,-- (DCnotes), this table has total payable amount column
rec.amount as dr,-- this column tells the paid amount
bil.amount as cr,-- this columen tell the payable amount
bil.balamount as balance,-- this column tells the net total of dr-cr columns
bil.billmonth as BillMonth,-- bill month column from bill table
bil.duedate as DueDate -- bill due date column from bill table
from
bills bil
inner join
Owners one on bil.ownerid = one.ownerid
inner join
Receipts rec on bil.spaceid = rec.propertyid
inner join
DCnotes dc on bil.spaceid = dc.property
inner join
BillTypes bt on bil.billtypeid = bt.billtypeid
inner join
Spaces sp on bil.spaceid = sp.spaceid
inner join
Locations lo on sp.locationid = lo.locationid
where
bil.siteid = '15'
This is the image of SQL query result:
This is the image of required data in report:
Please check attached images of required data and SQL query result

outer query to list only if its rowcount equates to inner subquery

Need help on a query using sql server 2005
I am having two tables
code
chargecode
chargeid
orgid
entry
chargeid
itemNo
rate
I need to list all the chargeids in entry table if it contains multiple entries having different chargeids
which got listed in code table having the same charge code.
data :
code
100,1,100
100,2,100
100,3,100
101,11,100
101,12,100
entry
1,x1,1
1,x2,2
2,x3,2
11,x4,1
11,x5,1
using the above data , it query should list chargeids 1 and 2 and not 11.
I got the way to know how many rows in entry satisfies the criteria, but m failing to get the chargeids
select count (distinct chargeId)
from entry where chargeid in (select chargeid from code where chargecode = (SELECT A.chargecode
from code as A join code as B
ON A.chargecode = B.chargeCode and A.chargetype = B.chargetype and A.orgId = B.orgId AND A.CHARGEID = b.CHARGEid
group by A.chargecode,A.orgid
having count(A.chargecode) > 1)
)
First off: I apologise for my completely inaccurate original answer.
The solution to your problem is a self-join. Self-joins are used when you want to select more than one row from the same table. In our case we want to select two charge IDs that have the same charge code:
SELECT DISTINCT c1.chargeid, c2.chargeid FROM code c1
JOIN code c2 ON c1.chargeid != c2.chargeid AND c1.chargecode = c2.chargecode
JOIN entry e1 ON e1.chargeid = c1.chargeid
JOIN entry e2 ON e2.chargeid = c2.chargeid
WHERE c1.chargeid < c2.chargeid
Explanation of this:
First we pick any two charge IDs from 'code'. The DISTINCT avoids duplicates. We make sure they're two different IDs and that they map to the same chargecode.
Then we join on 'entry' (twice) to make sure they both appear in the entry table.
This approach gives (for your example) the pairs (1,2) and (2,1). So we also insist on an ordering; this cuts to result set down to just (1,2), as you described.