Use tekst from table depending on number in other table using Access - sql

I feel stupid asking this, but I really need an excample on how to get a value of a field in one table (in the end in my report) depending on a value of a field from an other table in Access.
So I have (for excample) a table:
Products and in my report I do a formule using the value of price (field of Products) and adding to that I must have the value of the field VAT-Type (a nummeric var, in the table VATS) depending on what is there in the record (of the one in the table Products) in the field VAT-Sort, also a nummeric var that must meet one of the values used in the field VAT-Type).
So in the report I must have something like:
Product: X Count Price'=(price+21%)'
where 21% comes from the dependensy between the field VAT-Type and VAT-Sort.
I know I can do something like result=select 'VAT-Sort' from 'VATS' WHERE 'VAT-Sort' = or equals 'VAT-type'
But how do I use it in a report of Access to get the right result?

You can use DLookUp:
Numeric data type:
DlookUp("Value","Vats","Vat_Type=" & Vat_Sort)
Text data type:
DlookUp("Value","Vats","Vat_Type='" & Vat_Sort & "'")
Or you can base your report on a query, say:
SELECT Value, Other, Field, names FROM Products
LEFT JOIN Vats
ON Products.VAT_Sort = Vats.Vat_Type
Edit re comments

Related

Calculating the number of like records in an unbound text box on a form. in MS Access 2016

I have an unbound text box [txt_AmendmentOF] on a form to count the total number of Amendments a specific record has in the database. So the user knows which amendment they are on. Just a simple you are on Amendment 3 out of 8. i have this calculation i am using in the Control Source field of the text box [txt_AmendmentOF]:
=IIf(IsNull([txt_Amendment]),0,Count([MIPR_Number]))
there is a Field on my table called [Amendment] its text box on the form is called [txt_Amendment]. I have the calculation return a zero in [txt_AmendmentOF] if [txt_Amendment] is null. I need it to count the record number [MIPR_Number] that are the same and return the total number of Amendments count in the [txt_AmendmentOF] text box. on my table i have private key field called [ID] it is an autonumber format. The problem with the code above is it is counting all the fields that have a [MIPR_Number] and returning the total row count of that. i am not an expert here so any help would be greatly appreciated.
Update to post..
I have also tried this and got an error in the text box
=IIf(IsNull([txt_Amendment]),0,Count([MIPR_Number]=[txt_MIPR_Number]))
Counting by a condition is one of the basic dataabase tasks. To get answers from a db, you have to query the database (and that is done by createing a query).
To count same[MIPR_Number]you have to group the data (a group contains same numbers), then count.
SELECT COUNT(id) as CountOfSameNr, [MIPR_Number] FROM Table GROUP BY [MIPR_Number]
Store this query as e.g CountMIPRNumber.
Now you have two options:
Use a Dlookup to get one value
=IIf(IsNull([txt_Amendment]),0,Dlookup("CountOfSameNr","CountMIPRNumber","[MIPR_Number] = " & [MIPR_Number]))
or add the query to form recordsource (join on [MIPR_Number], "SELECT * FROM TABLE" is forms query)
SELECT CountMIPRNumber.CountOfSameNr, TABLE.* FROM TABLE LEFT JOIN CountMIPRNumber ON TABLE.[MIPR_Number] = CountMIPRNumber.[MIPR_Number]
and reference the count field
=IIf(IsNull([txt_Amendment]),0,[CountOfSameNr])

MS Access - Query - Replace value

One of the fields contains ID of partner organisations. Wherever the field is populated it's one of the partner organisations. If the field is blank, it means it's the parent company. In my query, how can I populate the blank records with the ID of the parent company?
The only thing I found was to create an expression in a new field:
SELECT Valid_Learner.LearnRefNumber, Valid_Learner.FamilyName, Valid_Learner.GivenNames, Valid_Learner.DateOfBirth, Valid_Learner.Ethnicity, Valid_LearningDelivery.FundModel, Valid_LearningDelivery.PartnerUKPRN,
Replace([PartnerUKPRN],"","parentComanyID") AS UKPRN,
Valid_LearningDelivery.DelLocPostCode, Valid_LearningDelivery.LearnAimRef
FROM Valid_Learner RIGHT JOIN Valid_LearningDelivery ON Valid_Learner.LearnRefNumber = Valid_LearningDelivery.LearnRefNumber;
The new field ("UKPRN") should (for the purpose of this question) have the string "parentCompanyID" whenever it's blank in the PartnerUKPRN field.
The result is the UKPRN field displays IDs where the ID is present in the PartnerUKPRN field, but shows "#Error" where it's blank in PartnerUKPRN.
If "blank" means NULL, then you can use NZ() in MS Access:
NZ([PartnerUKPRN], "parentComanyID") AS UKPRN
This would be the "normal" way to write this logic. I don't know why REPLACE() would return an error.

DLookup: Criteria returning blank values

I am trying to create an expression in Access 2016 to return a value from another table when a key is matched from the current table. I am sure it is syntax related, but am at a loss....
I want to add the receipt date (in tbl_RECEIPTS) as a column in tbl_POs based on the key value from the two tables being equal. INNER JOIN doesn't work because if we have not received the item, the field returned by DLookup should be blank.
Here is what I have:
The key is a string value in both tables.
DLookUp('[DATERECEIVED]',"tbl_RECEIPTS"," '[tbl_POs].[KeyVal]' = '[tbl_RECEIPTS].[KeyVal]' ")
The query runs, but returns a blank value for every record.
Any help would be GREATLY appreciated!
It could be:
DLookUp("[DATERECEIVED]","tbl_RECEIPTS","[KeyVal] = '" & [tbl_POs].[KeyVal] & "'")
I found it!
Sorry to answer my own question but What worked was using a LEFT JOIN with the tables.
The result will return blanks in the new date field when no corresponding key value is found.

Displaying different table values depending on the value of another table/column

I'm quite new to SQL and generally can find my way with basic stuff, but this time I'm kind of stuck...
I'm trying to retrieve (and display) the different configurations of an online app that are stored in a MSSQL DB.
I have to look at the value of a certain table and column (let's call it "configName.id"), and depending on the value returned (negative, positive, NULL), I have to match it in different tables and display one of 3 options in the same column.
I tried using CASE, but I don't want to display 3 different columns; I want to query different tables, and display the results in a single column. The displayed column name should be "Configuration Name".
In basic algorithm language, this would be:
if (configName.id > 0)
-> Display the corresponding value from table "a"
if (configName.id < 0)
-> Invert the value returned to be positive, display the corresponding value from table "b"
else
-> Display "NULL" as results.
My challenge is that regardless of the results returned from any table, I must display it under my report column "Configuration Name".
Any help would be really appreciated, thanks!
It would be something like this
select coalesce(a.value, b.value) as value
from configname left join
a
on a.id = configname.id and configname.id > 0 left join
b
on b.id = abs(configname.id) and configname.id < 0;

How to create calculated column with data from another list

I have the following situation: List A has two columns (Name, Amount) and in List B (Name) I want to add a calculated column which should be the sum of all entries in List A that have the same name as in List B. Example:
List A:
NAME Amount
L0011 100
L0011 50
L0020 234
So in List B I want the calculated column to show:
NAME Amount
L0011 150
L0020 234
How can this be done? Workflow (as soon as I add/mod an entry in List A, update List B) or something else? Thanks
lem.mallari's answer is a huge pain unless you can assume that the Amounts in List A never change, since it's not tracking whether an item has already been added to the sum. There is no way for a Workflow to iterate through a SharePoint list, which means there is no easy way to calculate the sum or average of multiple list items.
The correct way to implement this will will require some development. The SharePoint Developer Training (2010, 2013) will actually get you most of the way there: an event receiver should trigger when items are added or changed in Lists A and B that uses SharePoint's API to go through List A and average values by Name, then update all (or just affected) items in List B. Alternatively, you can use JavaScript to display the sum of all entries in List A that have the same name as the item in List B as long as all the data is displayed on your page. If you're handy with XPath and InfoPath, you could add List A as a secondary data source to List B's form and select only applicable items in List A to sum from.
But if we're talking Workflows, here's the "workflow only" method. This was tested and successful in 2010. Create custom List C with the following columns:
Title (string, mandatory, enforce unique values)
TotalItems (integer, mandatory, default 0)
Sum (number, decimal places however you want, mandatory, default 0)
Average (calculated, =IF(TotalItems=0,0,Sum/TotalItems)) (optional)
Replace the Name columns in Lists A and B with lookup columns pointing at List C. Delete the Amount column in List B, instead including the Sum column as an additional column. Add the following columns to List A, and ensure that users cannot change them directly. This can be restricted by making InfoPath forms or by making alternative view and edit forms.
AmountArchive (number, identical to Amount, default 0)
AmountHasBeenSubmitted (yes/no, default no)
Create a Workflow to run each time an item is created or modified in List A. Use these commands (I'm using a list for readability; it was getting ugly when formatted as code):
If Current Item:Amount not equals Current Item:AmountArchive
Set Variable:Item Count to (Data source: List C; Field from source: TotalItems; Find the List Item: Field Title; Value: Current Item:Name(Return field as: Lookup Value (as Text)))
Calculate Variable:ItemCount plus 1 (Output to Variable: ItemCount)
Calculate List C:Sum (similar settings as above; be sure to use Lookup Value (as Text) and not String!) minus Current Item:AmountArchive (Output to Variable: SumWithoutValue)
Calculate Variable: SumWithoutValue plus Current Item:Amount (Output to Variable: NewSum)
If Current Item:AmountHasBeenSubmitted equals No
Set AmountHasBeenSubmitted to Yes
Update item in List C (Set TotalItems to Variable:ItemCount; Set Sum to Variable:NewSum; Find the List Item in the same way of Field:Title; Value: Current Item:Name(Return field as: Lookup Value (as Text))
Else
Update item in List C (don't do anything to TotalItems; use the same logic to set Sum to Variable:NewSum)
Set Amount to Current Item:AmountArchive
This can't be done using calculated columns because calculated columns can only be used for columns on the same list.
Using SharePoint Designer Workflows you can just use Create List Item and Update List Item actions so that whenever a user adds a value for L0011 the amount will be added in another list's column which contains the previous amounts already.
Let me know if you need a more detailed answer for the SharePoint approach and I'll provide you a step by step instruction on what to do.
What about using the DSum function? https://support.office.com/en-us/article/DSum-Function-08F8450E-3BF6-45E2-936F-386056E61A32
List B
NAME Amount
L0011 =DSum("[Amount]","List A","[NAME]=''" & [NAME] & "'")
L0020 =DSum("[Amount]","List A","[NAME]=''" & [NAME] & "'")