Filling not existing data with 0 SQL / Access - sql

Please see below explanation of my problem. I have 2 tables.
[TABLE1: LocationsOFproducts - Keep data about location of products and quantity][1]
[TABLE2: Datahistory - keep data about stock movement ( removing/adding product from/to stock )][2]
[QUERY1: SumDataHistoryQuery - Making Sum of Products moved from the same location][3]
QUERY2: TOTAL QTY - Counting how many products left in some location after stock movement
SQL Code:
SELECT LocationsOFproducts.[Bay no]
,LocationsOFproducts.[Product Code]
,LocationsOFproducts.LocationQTY
,SumDatahistoryQuery.SumOfQTY
,([LocationQTY]) + ([SumOfQTY]) AS TOTALQTY
FROM LocationsOFproducts
INNER JOIN SumDatahistoryQuery ON (LocationsOFproducts.[Product Code] = SumDatahistoryQuery.[Product Code])
AND (LocationsOFproducts.[Bay no] = SumDatahistoryQuery.[Bay no])
AND (LocationsOFproducts.[Product Code] = SumDatahistoryQuery.[Product Code])
GROUP BY LocationsOFproducts.[Bay no]
,LocationsOFproducts.[Product Code]
,LocationsOFproducts.LocationQTY
,SumDatahistoryQuery.SumOfQTY
,([LocationQTY]) + ([SumOfQTY])
ORDER BY LocationsOFproducts.[Product Code];
RESULT:
I expect a little bit different result.
My query should check is there any more value with Bay no,product code and QTY in Datahistory table, if not I want to fill that space with data from LocationOfproducts table and in the field SumOfQTY fill those
values with 0 to make a sum in TOTALQTY column.
Please see below what I need to get:
Please see query what I need to get - I maked that in Photoshop by cutting and pasting fields:
Can anyone know how to write the right query?

Related

How to add 2nd price column in SQL when info is normally stored on 2 separate rows

I currently have a very simple SQL script, which provides the sell price for a special customer of ours, who gets Priceline "J". I'd like to add a column of Retail pricing as well for them to reference, which is normally Priceline "R". My query currently looks like this:
SELECT RS_PCL.SKU,
RS_PCL.SKU_DESC,
RS_PCL.PACKAGE,
RS_PCL.PRICE AS [Sell Price],
RS_PCL.STD AS [Start Date],
RS_PCL.END AS [End Date]
FROM RS_PCL
WHERE RS_PCL.PRICELINE = "J"
Would anyone be able to help me figure out how I could add the "R" price line as another column instead of separate rows?
I can add WHERE RS_PCL.PRICELINE IN ("J","R") but it would create a separate row for each Retail price, instead of in the column next to it. I've seen examples of a separate SELECT CASE WHEN, but not sure exactly how the syntax works.
The prices are always going to have the same start date, so it would just need to join where the SKU matches and the Start Date matches.
NOTE : IM sorry I accidentally edited your answer, not my question...
Revised: Running into errors with this code still, saying "Your query does not include the specified expression 'GL Type' as part of an aggregate function" or would say each field that isn't included in the group by clause
SELECT RS_PCL.[GL Type],
RS_PCL.SKU,
RS_PCL.[SKU Desc],
RS_PCL.Supplier,
RS_PCL.[Case UPC],
RS_PCL.[Pack UPC],
RS_PCL.[Unit UPC],
RS_PCL.PDCN,
RS_PCL.Package,
RS_PCL.[Price Start Date],
RS_PCL.[Price End Date],
Iif( RS_PCL.PRICELINE = "J" , RS_PCL.Price , Null) AS [Sell Price],
Iif( RS_PCL.PRICELINE = "R" , RS_PCL.Price , Null) AS [Retail Price],
RS_PCL.Cost,
RS_PCL.Tax,
RS_PCL.Freight
FROM RS_PCL
WHERE (RS_PCL.PRICELINE IN ("J","R"))
Tested the Self Join query listed below, I keep getting a "Syntax Error in FROM Clause" with this query.
SELECT J.*, R.R_PRICE FROM RS_PCL AS J
INNER JOIN SELECT (RS_PCL.SKU, RS_PCL.[Price Start Date], RS_PCL.Price AS R_PRICE FROM RS_PCL WHERE RS_PCL.PRICELINE = "R") AS R
ON J.SKU = R.SKU AND J.[Price Start Date] = R.[Price Start Date]
WHERE RS_PCL.Priceline = "J"
SELECT CASE does not work in Access query. Use IIf() or Switch() or Choose().
Perhaps a CROSSTAB query or emulate CROSSTAB with expressions to create fields. Presuming, as indicated in question title, there is one "J" and one "R" record for each data combination:
SELECT SKU, SKU_DESC, PACKAGE, STD, END,
Max(IIf(PRICELINE = "J", PRICE, Null)) AS J,
Max(IIf(PRICELINE = "R", PRICE, Null)) AS R
FROM RS_PCL
GROUP BY SKU, SKU_DESC, PACKAGE, STD, END
Or a self-join, assuming only fields needed as unique identifier are SKU and STD:
SELECT J.*, R.R_PRICE FROM RS_PCL AS J
INNER JOIN (SELECT SKU, STD, PRICE AS R_PRICE FROM RS_PCL WHERE PRICELINE = "R") AS R
ON J.SKU = R.SKU AND J.STD = R.STD
WHERE PRICELINE = "J";
This would be useful on a report but useless for a data entry form.
Yet another approach would use DLookup() domain aggregate function. Domain aggregate function can cause slow performance in query or form but the dataset would be editable.

I'm having issues getting the NZ function working in a query

I'm trying to tie a description to group codes to use in another table. Unfortunately the data is from a very old database and didn't have very good requirements for fields when it was initially created. So now I have a number of fields for part number group codes that were blank. I'm trying to convert these null values to say "blank". I've tried this many different ways and cannot get the nz function to modify the data in any way.
In the provided code snippet I have tried using the nz function only after select, only after from, and in both places as shown.
SELECT [Part Numbers].Part, nz([Part Numbers].Group,"Blank"), [Group Codes].Description
FROM [Part Numbers]
INNER JOIN [Group Codes] ON nz([Part Numbers].[Group],"Blank") = [Group Codes].[Group Code];
That query doesn't return records where Group field is Null. It can't even be displayed in query design with that join.
Consider RIGHT JOIN:
SELECT [Part Numbers].Part, Nz([Part Numbers].Group,"Blank") AS Expr1, [Group Codes].Description
FROM [Group Codes] RIGHT JOIN [Part Numbers] ON [Group Codes].[Group Code] = [Part Numbers].Group;

Percentage column not displaying in Access Listbox

I have a listbox on a report that's effectively summarizing another table, grouped by a short list of reasons. I have a column for the reasons, and a column for the number of times each reason occured. I want to have a column for what percentage those reasons constitute, but this column is not displaying - moreover it is giving the previous column (count by reason) wrong numbers.
Before editing, my code (which worked perfectly) was;
SELECT Reasons.Reason, Count([Master Data].ID) AS [Count]
FROM Reasons INNER JOIN [Master Data] ON Reasons.ID = [Master Data].[Lateness Reason]
GROUP BY Reasons.Reason;
I edited it to be;
SELECT Reasons.Reason, Count([Master Data].ID) AS [Count], Format(Count([Master Data].ID)/Count(AllData.ID),'\P') AS Percentage
FROM [Master Data] AS AllData, Reasons INNER JOIN [Master Data] ON Reasons.ID = [Master Data].[Lateness Reason]
GROUP BY Reasons.Reason;
But as mentioned, the third column doesn't show and the number in the Count Column is now wrong too.
Can someone explain why this is and what I should do to fix it please?
EDIT: I have worked out that the incorrect number showing in the 'Count' column is actually the correct number multiplied by Count(AllData.ID) although I can't understand why this would happen.
Correct/desired | Actual Output
value for "Count" | Value
___________________|___________________
10 75500
4 30200
1 7550
20 151000
3 22650
7 52850
Try using the correct syntax for Format:
Format(Count([Master Data].ID)/Count(AllData.ID),'Percent') AS Percentage
And you will probably have to use a subquery to obtain the distinct count og the table with the smallest count of joined records ([Master Data]?).
Edit:
If your first solution seems slow, try this:
SELECT
ID,
Reason,
T.ReasonCount / (SELECT Count(*) FROM [Master Data])
FROM
Reasons
INNER JOIN
(SELECT [Lateness Reason], Count(*) AS [ReasonCount]
FROM [Master Data]
GROUP BY [Lateness Reason]) AS T
ON
T.[Lateness Reason] = Reasons.ID
GROUP BY
ID,
Reason,
T.ReasonCount

Need MS Access Form Field to automatically Calculate and Allocate Costs based on given Parameters

Below is my mock database that I am using. I have four different tables: Tbl_MainDatabase, Tbl_InsuranceCoverage, Tbl_MatterDetail, and Tbl_PaymentProcessing.
What I want -
I want my form to determine the remaining Retention Limit (i.e., Retention Limit for the applicable policy - sum of invoices for the same Claim Number )
According to the mock database, the required answer should be [ $2500 - (300+700+355)] as highlighted for your convenience
What I tried
I used the help of Graphical representation through the following query:
SELECT [Claim Number], Sum([Net Invoice Amount])
FROM [PaymentProcessing]
GROUP BY [Claim Number]
This method works to show me how much I spent per claim number so far in the form of a graph. However I want to display the remaining amount.
Any Help is appreciated :)
I am one month old at using Access. But I am trying my best to learn
Thank you in advance!
SELECT
IC.[Retention Limit]-SUM([Net Invoice Amt]) AS Remaining, MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
FROM tbl_InsuranceCoverage IC
INNER JOIN tbl_MatterDetail MD ON ic.InsuranceID = MD.Policy
INNER JOIN tbl_PaymentProcessing PP ON MD.MatterDetailID=pp.MatterDetailID AND MD.[Claim Number]=pp.[Claim Number]
GROUP BY MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
See if this works. Havent tested it but seems simple. You can remove the extra columns, but this will hlep you understand joins a bit
For All the New users The above code by #Doug Coats works perfectly.
Make Sure All the Foreign Key and Primary Keys is linked in the Relationship Property. ( One of the way To do this in the Query is - Right click on the Query and select Design View --> Right click again on the grey space and Select Show all Tables Now Drag your Primary Key of the table and drop at the foreign Key on the other table --> This will create a relationship between both for the Query Purpose.
This will also Prevent Data from Duplication in the query then use a similar code as described by Doug Coats in the above comment in the SQL View
SELECT [Insurance Coverage].[Retention Unit]-Sum([Net Invoice Amount]) AS Remaining, [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy
FROM (([Main Database] INNER JOIN [Matter Detail] ON [Main Database].[Database ID] = [Matter Detail].[Short Name]) INNER JOIN [Payment Processing] ON ([Matter Detail].[Matter Detail ID] = [Payment Processing].[Matter Detail ID]) AND ([Main Database].[Database ID] = [Payment Processing].[Short Name])) INNER JOIN [Insurance Coverage] ON [Matter Detail].Policy = [Insurance Coverage].[Insurance ID]
GROUP BY [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy;
You can then display this query in the form - I am still evaluating best way to display this query probably in a Combo Box (Not sure if any other controls has a row source)
Thank you

Trouble with WHERE EXIST subquery of a LEFT JOIN

I am trying to run a Left Join in the MS Access SQL. I am trying to Left Join my "OldPE" table to New "1 PE" table and update my column labeled "Line Num". There is no primary key in these tables so I am linking them through a series of conditions. Here is my code so far (excuse the poor formatting I am new and still learning SQL).
UPDATE [1 PE]
LEFT JOIN OldPE ON ([1 PE].SumRes = OldPE.SumRes)
AND ([1 PE].[Project Code] = OldPE.[Project Code])
AND ([1 PE].[DeptID] = OldPE.[DeptID])
AND ([1 PE].[Res Code] = OldPe.[Res Code])
AND ([1 PE].[Explain The Cost] LIKE OldPE.[Explain The Cost])
AND ([1 PE].Notes LIKE OldPE.Notes)
SET [1 PE].[Line Num] = [OldPE].[Line Num];
There are a lot of rows that have null or blank values in their "Explain The Cost" and "Notes" columns. I used a like statement because some of the notes that I want together vary slightly due to spelling mistakes and such. However now that I use the "like" it won't return the rows with a null value for these columns. The SQL code wont accept a WHERE EXISTS (I may also just be writing it wrong).
How do I get these null values to still be returned while using the Like command
Use ISNULL to join back to the original value if it is null. (This will include the null values in the results.)
AND ([1 PE].[Explain The Cost] LIKE ISNULL(OldPE.[Explain The Cost],[1 PE].[Explain The Cost]))