MS Access Sum and IIF expression - ms-access

I'm with a non-profit. We divide the state up into 16 regions for administrative purposes. I'm trying to find out how many members live in each region. We have 4 different types of members too. There's a table that lists all the members. There is also a table in which we have listed all the towns in the state and put in which of our regions the town is in. For the first member type the record has the value "1" in the TYPE field. I'm trying to write an expression that basically says this. If the TYPE field has a "1" in it, then the condition is true, return 1. Else return 0. Then sum up all the ones.
I didn't build the database or the query. This is the expression that was already there: INDIVIDUAL: Sum(IIf([Membership.TYPE]=1,1,0)) The sum that it comes up with just doesn't make sense.
Edit: I hope I did this right. Here is a table showing what information the query returns except for the 502 and the 96 which I put there as a check. The values in that one column add up to 502 but they should add up to 674. The 96 should be 113.
enter image description here

Related

Access 2016 Table Calculated Field

I have a table containing the following: Five Y/N fields and a calculated field [Priority Results] that totals the number of 'Yeses' from those five y/n fields. I'm trying to create another calculated field that will return a value of Low, Medium or High dependent on the number of boxes that have been checked. [Priority Results] currently returns the values 0 through -5. Low = 0 & -1, Medium = -2, High = -3 or lower. I've tried SEVERAL different versions of If/Then, If/Else, Iif statements and always receive a syntax error. I've read a lot of different sites and the following expression seems to be the most commonly used, but I'm still getting the error. Anyone have any ideas? I've even tried this statement on a non-calculated field and can't get it to work.
IIf([Priority results]<="-1","Low",IIf([Priority results]="-2","Medium",IIf([Priority results]>="-3","High")))
Here are the calculated field [Priority results] properties.
Expression:
[Class Non-Attendance]+[Instructor Referral]+[Late Registration]+[Low Starting GPA]+[Talon Log-in]
Result Type: Long Integer
enter image description here
The part of the table this question relates to has the following fields:
Class Non-Attendance: Yes/No
Instructor Referral: Yes/No
Late Registration: Yes/No
Low Starting GPA: Yes/No
Talon Log-In: Yes/No
Priority Results: Calculated field counting the Yes/No fields above
Priority Outcome: Calculated field (that isn't working) prioritizing based on Priority Results
Don't put parameters for number fields in quotes.
Consider:
IIf(Abs([Priority Results])<=1, "Low", IIf(Abs([Priority Results])=2, "Medium", "High"))
In a query or textbox, expression could be:
Switch(Abs([Priority Results])<=1, "Low", Abs([Priority Results])=2, "Medium", True, "High")
Parts of the question still confuse me, which is why this answer will be brief. You have a calculated field PriorityOutcome based on another calculated field PriorityResults and that is the problem. Access doesn't calculate PriorityResults before calculating PriorityOutcome. Instead Access says PriorityResults doesn't exist yet and passes null to PriorityOutcome resulting in either an error or a silent fail.
There are several fixes you can mix and match. You can repeat the calculation for PriorityResults inside PriorityOutcome: wasteful but often the fastest solution. You can also add a code module with public functions to do part or all of the calculations. Then refer to those public functions in your calculated fields Access intellisense can find public functions.

Tableau's functions - how to find an equivalent to IF EXISTS

I'm creating a Tableau Dashboard with 'buttons' which are coloured red or green based on certain criteria and what is selected in the filters. The filters are just a way to select different offices in different regions and when selecting an office the buttons should change colour depending on whether the targets for the different metrics have been hit for that office or not.
The navigation buttons on Tableau won't accommodate this so I've made a work around. For each 'button' I've created a worksheet with just the text of the metric name on the Label mark and a calculated field on the colour mark. I've then added the worksheet to the Dashboard and added an action to go to the corresponding metric dashboard when the 'button' is clicked on.
The issue I'm having is the conditional colouring of one of these metrics. This metric is based on stock levels. For each office there are multiple categories of stock types, each with a corresponding target, with multiple 'bins' in each category. I want the button to turn red if ANY of the combined total of stock in the bins for one category is over the target for that category for that office.
To try and type it logically-
For the currently filtered data: IF EXISTS(FOR EACH OFFICE( FOR EACH CATEGORY: [SUM(BinValue)< CategoryTarget])) THEN 'Green' ELSE 'Red'
I've tried to translate that logic into Tableau's functions in a calculated field and have the following:
SUM(INT({INCLUDE [Category]:Min([CategoryTarget])} > {INCLUDE [Category]:SUM(BinValue)}))
This colouring is correct when I add the Office Name and Category pills to the worksheet to test my logic however when I remove the pills the colouring isn't correct. Something seems to be going wrong when I try to sum the number of categories that are within target levels over all offices and targets.
I've tried so many iterations of the following functions and have been going around in circles for days now:
INCLUDE, EXCLUDE, FIXED, IF, SUM, INT
If anyone knows how to do this properly or even just a different way of being able to conditionally colour buttons on a dashboard I would be incredibly grateful.
The structure of my data is as follows with some dummy data as an example:
Region
SubRegion
Office
Category
Bin
BinValue
CategoryTarget
North
NorthWest
Manchester
Toys
B123
30
50
North
NorthWest
Manchester
Toys
B456
40
50
So for a Stock Level metric selecting any of ALL/North/NorthWest/Manchester filter options should flag as red due to the total of the bins in one category in an office being higher than the target amount for that category for that office.
I've updated my calculated field however I'm still having issues with the grouping showing as true/false correctly.
This is what it is now:
MAX( {INCLUDE Category, Office:Sum(BinValue)} > {INCLUDE Category, Office:MIN(CategoryTarget)} )
With True showing as Red and False Green (we want to be below target hence the green).
When working on the example to showcase the issue I managed to get it working.
I ended up using the following logic:
max({EXCLUDE [Bin]:SUM([Bin Value])} > [Category Target])
This meant that even if most of the Offices in the filter were within their stock level targets, if there was one with stock levels over target the 'button' showed as red.
I published the example I've used anyway in case it helps others in the future.
Link to the Tableau Public dashboard:
https://public.tableau.com/views/ConditionalColouring/Dashboard1?:language=en-GB&:useGuest=true&:display_count=y&:origin=viz_share_link
Thank you very much for the help!
To work with logical conditions, such as testing whether a condition holds for any (or every) record in a group of data rows, it helps to understand that Tableau treats the boolean value "True" as greater than the boolean value "False".
Once you get comfortable with that idea, you can use the functions MAX() (or MIN()) to test whether a condition holds for any record (or for every record, respectively). So MAX(False, False, True, False) is True.
So to tell if any records have an actual value below their target, test MAX([Actual Value] < [Target Value])
You can then combine this idea with dimensions on the viz (or LOD calcs if necessary) to group the data records appropriately before testing your conditions. If you work with the same conditions repeatedly, this type of calculation can be very useful for defining sets that get used in multiple places.
One technical caveat, if your condition test ever evaluates to NULL, then those null values are ignored by MIN() and MAX() - just like other aggregation functions do. So for example, you could test whether every record satisfies a condition using MIN() and get a possibly misleading result if all the non-null values are True (so MIN() reports True). MIN(TRUE, TRUE, NULL, TRUE) = TRUE. If your condition can evaluate to NULL, and you don't want to ignore nulls, but instead treat it as, say, the same as False, then you can use the IFNULL() function to provide a default value for your condition.
As an example, MIN(IFNULL([Actual Value] > [Target Value], FALSE)) returns True only if every record has a value above its target, treating any records with missing values or targets as failing the condition - i.e. not exceeding the target. The choice of whether to have a default value for a condition, and what it should be, are problem dependent of course. If your data does not have null values, you don't have this complication to consider.
Though the data you have given is very less, yet I think this calculation field you require
IF { FIXED [Region], [Sub-Region], [Office], [Category] : SUM([Bin Value])}
> {FIXED [Region], [Sub-Region], [Office], [Category] : MIN([Category Target])} THEN 'RED' ELSE 'GREEN' END
This is based on assumption that for every group of region/sub-region/office/category target value will be same in each row within the group. Therefore MAX/AVG etc. will all work in place of MIN used in the calculation.
See I added two rows in your data
and result

Searching ALL ROWS in a Group using IIF Expression

I am working on a report that displays patient names (as groups with drilldowns) and several fields related to their visits. I have created a column in the report to display whether or not a specific value appears in the 'LocationID' column. The expression I used is
=IIF(Fields!LocationID.Value="WELL","Y","N")
I thought this was working great, it displays Y or N next to each name to let me know if 'WELL' was in their 'LocationID'. I checked several to ensure that this was going to work and discovered that there was a LocationID code of 'WHS' and since I have the rows ordered by Name and LocationID if there was a WHS visit it shows up at the top of the group and my expression is only seeing this top item. How can this expression be written differently so that it searches the entire result of each group? Depending on the date range a patient may have one visit or they may have ten. I need to check all visits that are returned. Perhaps there is a better method. Thanks in advance.
I agree with jimmy8ball that the easiest way to solve most issues like this is to push some logic back into the SQL layer.
However, if you really want to do this via SSRS functionality, then you could implement a substring search against a lookupset. Assuming you have a patient id in your dataset that is unique for each patient (I hope your group isn't on the name) then...
=Iif(InStr(Join(Lookupset(Fields!patientid.Value, Fields!patientid.Value, Fields!LocationsID.Value, "dataset"), ","), "WELL") > 0, "Y", "N")
Which says, "Search through the dataset for all rows related to my patientid, join every location into a comma deliminated string, search the string for the text "WELL" and return "Y" if it's found.
Obviously if you have locations in your dataset like "WELLY", these will become false positives and you'll have to implement some more nested logic. Try appending a value (perhaps !) to the lookupset return field so that you can search for "WELL!" or some other terminator character.

SSRS Report Builder IIF error with aggregate

I've been struggling with an IIF error when trying to create a variable aggregate.
I'm using Report Builder 3.0
I have a report where users determine what fields are in a report. These fields are passed as a multivalue parameter. I use a lookup from a different dataset to determine its placement in the report, and using the same order dataset to determine if the field is numeric or not (meaning I want to sum the value based on row-level grouping). The headers pull in using the same field lookup, which works fine. At the row level I'm trying to return either the sum of the field value based on row grouping, or if non-numeric, return the value. Based on similar posts I understand that both the true and false parts are processed. I attempted to offset this error by nesting another IIF. If I remove the sum function the data returns non-numeric data fine. However if I include the sum function numeric data is processed fine however non-numeric data returns #error.
What am I missing?
Here is a definition of the data I'm referencing below:
lookupvalue: returns the fields selected by the user based on predefined order in a stored procedure.
Fieldisnumeric: indicates if the field selected is numeric or not, 0 is false, 1 is true
Fielditem: the field item in the tablix being referenced
dtsselectedfields: the dataset I'm looking up the column order and numeric properties of a field.
The number 1 indicates the first position in the variable count of fields selected by the user. Additional fields are hidden based on the count of fields passed in the parameter and are incremental (e.g 1-n).
=iif(Lookup(1, Fields!LookupValue.Value,
Fields!FieldIsNumeric.Value,"dtsSelectedFields")=0,
Fields(Lookup(1, Fields!LookupValue.Value, Fields!FieldItem.Value,
"dtsSelectedFields")).Value,iif(Lookup(1, Fields!LookupValue.Value,
Fields!FieldIsNumeric.Value, "dtsSelectedFields")=0,
Fields!MV.Value,sum(Fields(Lookup(1, Fields!LookupValue.Value,
Fields!FieldItem.Value, "dtsSelectedFields")).Value)))
****edit 12/1/2015****
For additional clarity, I'm providing additional details. Below is 'dtsSelectedFields' dataset.
FieldItem_____LookupValue_____FieldIsNumeric
Item1Desc__________1__________________0
Item1Total__________2__________________1
Item2Desc__________3__________________0
Item2Total__________4__________________1
Let's say I have one column of data, and this column would first look for a LookupValue of 1. This would return the FieldItem, 'Item1Desc'. Because this field is not numeric, I would want to return the value of Item1Desc. However let's assume my first selection was actually 'Item1Total' and I don't want to return the non-numeric Item1Desc field. In this case, because 'FieldIsNumeric'=1 indicating a numeric field, I want to take the sum of this field.
Is it possible to nest an aggregating function in an IIF statement on only one part of an IIF statement? I.e. the true part or false part?
And if so, what am I doing wrong?
An example of the tablix:
sample layout
Column 1 Header____________Column 2 Header___________Column 3 Header
Column 1 Data______________Column 2 Data_____________Column 3 Data
Sample data
Product___________________Country of Origin_________________Units
ABC Envelopes___________________China______________________15
LMN Packets_____________________India_______________________30
In the example above, user selects 3 columns, 'Product', 'Country of Origin', and 'Units'. There are other fields available that would cause multiple rows if I grouped by them in the stored procedure (for example acquisition price). Based on the lookup I return the column description as a header. The row-level detail is described as above (e.g. Return the product name and country of origin, but sum up the units).
As a workaround for my issue above, I found an (ugly?) solution.
As mentioned above, a user can select any number of columns and the report organizes them in columns based on a predefined order according to a stored procedure. (E.g. a product description would come before the sum of the units if those two columns were chosen, but a product ID may come before the product description, but only if the ID was chosen.)
For every possible number of columns a user can select, I added two columns in the report (i.e. two for each field).
The first two columns will reference the lookupvalue=1. I then set the expression of each field in the detail to 1) a sum of the value, or 2) the value itself. I then set the column visibility to the results of the 'FieldIsNumeric' column. So the summed numeric column which would return an error for non-numeric data would be hidden when FieldIsNumeric=0, and the non-numeric column referencing the lookup value =1 would be shown, and vice versa.
Needless to say additional columns would follow the same logic in sets of two, each referencing the sequential lookup value (e.g. columns 3 and 4 would reference lookupvalue=2, columns 5 and 6 would reference lookupvalue=3, and so forth. Each column within the matching pair would be displayed or hidden based on the returned value of FieldIsNumeric in the same lookup dataset.
I'm definitely open to suggestions, but thought I'd post this as a workaround solution.

SSRS Report - get distinct count of a string in a filtered group

I have a filtered group inside my tablix called Counties. My report is working well and produces the results of:
County PY CY Difference
Scott 141 143 2
Cape 90 98 8
North 78 88 10
I now need to obtain the distinct count of my counties. In my example, this would be 3.
I have scoured many blogs and have tried several things I have read.
I have tried using =CountDistinct(Fields!County.Value). When I put it in a line below my counties, but within the group, I get a 1 below each county name. When I put it in a line below my counties, but outside the group with =CountDistinct(Fields!County.Value, "Counties"), I get the error message "The Value expression for the text box ‘Textbox487’ has a scope parameter that is not valid for an aggregate function. The scope parameter must be set to a string constant that is equal to either the name of a containing group, the name of a containing data region, or the name of a dataset." I tried putting Cint() around it too and still nothing.
I have added a new column and used the distinct count function and got a 1 for each county. That is fine until I try to add them up in the row below. I used =Sum(ReportItems!Textbox486.Value) and got the error message "The Value expression for the textrun Textbox486 uses an aggregate function on a report item. Aggregate functions can only be used on report items contained in page headers and footers."
I have a feeling this is something that will need to be done with code. Honestly, I don't know code. I have always gotten by without it, until now.