SSRS - Sum of an aggregated field - sql-server

I have a report, that shows the individual sales commission for each employee.
The expression for the Sales Commission is:
=Sum(Fields!Total_Comission.Value)*Parameters!Distribution_Factor.Value*Fields!Individual_Factor.Value
Now I want to add a total for this field. If I just right click the cell and click on Add Total, it works but gives out the wrong total.
If I try to sum the field like this:
=Sum(Reportitems!GO_Prov.Value)
I get the error:
The Value expression for the textrun 'Textbox93.Paragraphs[0].TextRuns[0]' uses an aggregate function on a report item. Aggregate functions can be used only on report items contained in page headers and footers.
Is there a workaround to sum the aggregated field of this tablix? Maybe with a code?
Thanks in advance.
Update1:
Unfortunately i don't know how to write custom codes. But I found this code:
Public Total_lookup_Sum As Integer = 0
Public Function Lookup_Sum(ByVal value As Integer) As Integer
Total_lookup_Sum = Total_lookup_Sum + value
Return value
End Function
The expression i used for the Sales Commission is now:
=Code.Lookup_Sum((Sum(Fields!Total_Comission.Value)*Parameters!Distribution_Factor.Value*Fields!Individual_Factor.Value))
And the expression for the field where i would like to get the sum is:
=Code.Total_lookup_Sum
Now i get the error:
There is an error on line 0 of custom code: [BC30205] End of
statement expected.
Is there a way to solve this?

Scenarios like these can be tricky in SSRS. From your description (even though the screenshot doesn't really show everything), I'm guessing that you've got rows grouped by salesperson. In your column that's calculating the commission, you've got a sum of "Total_commission", but you've just got the "Individual_Factor" value not aggregated. Again, having a guess, but each underlying row (by employee) must have the same "Individual_Factor" value (so actually using Min(Individual_Factor) would give the same result).
But then, when you try and just take the same formula (or even a derivation of the formula), and make an overall aggregate of all of the rows, how does SSRS know which "Individual_Factor" value to use? You don't want Min() or Max(), because that would just be the lowest or highest value across all of the salespeople.
Your suggestion of a workaround via code is generally the way that I approach this. You need a report variable, something like "Commission_Grand_Total", and then you need a function in the report code that accepts 1 parameter, and in the function you'll add the parameter value to the variable. The easiest thing to do is to make the parameter the return value of the function.
Then, in the field where you currently have your commission formula (on the salesperson row), the expression in that field becomes =TheFunctionYouCreate((Sum(Fields!Total_Comission.Value)*Parameters!Distribution_Factor.Value*Fields!Individual_Factor.Value))
By passing the formula to the function, you're achieving two things:
The function will take each salesperson's calculated commission and add it to your report variable
The function will output the parameter value that you passed in (since you want to display the calculated commission amount on each salesperson's row)
Lastly, to display the overall total, the expression for that field is just the report variable that holds the overall total (that has been cumulatively added to as SSRS wrote out each salesperson's record)
TIP: I sometimes do this same sort of thing, but if I don't want the row-by-row value to be shown (I just want the cumulative total to be calculated), just put the expression that calls the function in a hidden column. SSRS will still run the function as it renders each row, but obviously it's just not displaying the result of the function.
Some MS reference for report variables and code
https://learn.microsoft.com/en-us/sql/reporting-services/report-design/built-in-collections-report-and-group-variables-references-report-builder?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/reporting-services/report-design/add-code-to-a-report-ssrs?view=sql-server-ver15

This is untested unfortunately but...
assuming you have a rowgroup for employee called EmployeeGroup then the expression would look like this...
=SUM(
Sum(Fields!Total_Comission.Value, "EmployeeGroup")
* Parameters!Distribution_Factor.Value
* FIRST(Fields!Individual_Factor.Value, "EmployeeGroup")
)
The inner expression reads as
Sum of Total_Comission with current employee group
... multiplied by Distribution Factor
... multiplied by the first individual factor with the current employee group
The outer expression just sums all the individual employee level sums.

Related

How to specify a column field in a calculated field formula when you have the same value evaluated as a count and a sum?

I am using a pivot table to summarize our status of completion of a project. The first value of the pivot table gives me a count of the entries in the spreadsheet column that have a value greater than 0. The next value of the pivot table gives me a count of the total estimated quantities from the spreadsheet. The third value gives me the sum of the entries from the same column of the spreadsheet that the first value uses in the pivot table. The final value of the pivot table is a sum of the total estimated quantities from the same column from the spreadsheet the second values uses for the pivot table.
My current working formula will only evaluate the SUM columns in the pivot table and is the following:
=iferror('Quantities Complete'/'Total Est Quantities',0)
This gives me a percent complete based on the SUM of those two columns from the spreadsheet. These values can differ because the first is a real value and the second is an estimated value. What I want is the below formula which I will put how the data is summarized in parenthesis for simplicity of understanding.
=if('Quantities Complete'(COUNT)='Total Est Quantities'(COUNT),1,iferror('Quantities Complete'(SUM)/'Total Est Quantities'(SUM),0))
This formula would allow me to evaluate if the count of complete items matches the total estimated items, if so the calculated field value is 100% regardless of actual sum values. Otherwise, it gives a percent complete based on sum value which is more accurate because each item can have vastly different values.
How can I refer to the 2 different uses of the columns in a calculated field formula?
I have tried the renaming the column headers to 'Items Complete' and 'Item Values' but the formula does not accept those and gave a parse error. I have tried using the "COUNTA of" or "SUM of" prefix for the column fields. I also tried typing the name as shown when I hover over the value field in the edit window which I tried in these methods: 'Quantities Complete' (Items Complete) and 'Quantities Complete (Items Complete)'. All of these yielded a parse error. I can't share my spreadsheet due to confidentiality requirements, but all I need to know is how to refer to the two different column headers that have the same name from what I can tell.

Is there any approach to get access the Sub report variable or to get SubReport element in main report?

I am writing an SSRS report in which I've a tablix that actually contain a subreport in one of its table cell. Now I want to understand to get this value as Sum on main report. For example, below is the student data:
Student Name | Total Subject | Obtained Marks (Sub Report)
XYZ | 6 | 35
ABC | 6 | 46
In above example, I am able to see the total marks of the first subject only. But I need to get the total form all 6 subjects from sub report. My tablix is already has Grouped by Student Name.
Below are the ways I tried to get it done:
Added another column in tablix and try to get the subreport as ReportItems! Subreport2, didn't work.
In the same column, I tried with Sum (Subreport2).
But since Subreport2 as report items are not accessible I'm not able to get it done.
UPDATE 1
I am using below expression to get sub-report value:
=ReportItems("Subreport2").value
The short answer is, no, you can't access fields from a subreport in the manner that you are attempting to. However, there is an easy way to get the values from that subreport that you may not have realized. The basic solution is to simply add another dataset to your report using the same query or stored procedure that is used in the subreport and getting the required data from that dataset. For example, you could then use a lookup function to match the data as needed. The lookup function requires four parameters detailed in the following expression.
= Lookup([SourceValue].Value, [DestinationValue].Value, [LookupValue].Value, "[DestinationDataset]")
The idea in your case would be to put your student name or ID field from the main report dataset in for source value, match that value in your subreport dataset for the destination value, get the value you need for lookup value, and the subreport dataset goes in parenthesis to indicate where to get the data from. So the following expression gives you an idea of what you need.
= Lookup(Fields!studentID.Value, Fields!studentIDSub.Value, Fields!ObtainedMarks.Value, "SubreportDataset")
Take a look at the documentation if you need any addition information.

Sum the value of aggregate function in SSRS report

I have a column that gets its value from Commission %(percentage is based on a customer # so it can change) multiplied by Profit column by using the following expression:
=Fields!Profit.Value * ReportItems!Commission%.Value
I need to get subtotal for the Commission Total column. When I try to total the commission I get the error:
"The Value expression for the textrun 'Textbox91.Paragraphs[0].TextRuns[0]' uses an aggregate function on a report item. Aggregate functions can be used only on report items contained in page headers and footers."
I then tried to SUM the value of the textbox by using =SUM(ReportItems!Textbox65.Value) but it would only grab the last result and not sum all of them.
The subtotal of the Commission Total column should be 14.64 not 2.13045. I am trying to total the Commission Total column.
Well, the problem is that aggregate functions like Sum don't like to operate on ReportItems. I think that the value in the Commission% column comes from an expression that uses elements (or even just one element) of the Fields collection, so you just have to use that same expression when calculating the total commission, for example
=Sum(Fields!Profit.Value*Fields!Commission%.Value)
I used the report wizard in design view in visual studio and exported to report server and ran, see attached image, commission total is correctly displayed without the use of reportitems.

Expression to get a percentage

I have a report which has a transaction type as a row group. There are two different types. I want to get the percentage of one type 2 compared to type 1.
I am not sure how to do this, I assume I need to use an expression which states the name of the transaction type and then make a calculation based on the other type.
So Instead of a total for July being 300, I would like the percentage of SOP+ compared to SOP-, so in this case 1.96%. For clarity, the figures in SOP+ are not treated as negative.
When you design a query to be used in a report, it is generally easier to work with different types of values being in separate columns. You can let the report do most of the grouping and aggregation for you. In that case, the expression would be something like this:
=Fields!SOP_PLUS.Value / Fields!SOP_MINUS.Value
Since they are both in rows in the same column, you have to use some logic to separate them out into columns and then do the operation.
You'll need to add two calculated fields to your dataset. Use an expression like this to get the values:
=IIf(Fields!TYPE_CODE.Value = "SOP+", Fields!SOP.Value, Nothing)
In other words, you will have new columns that have just the plus and minus values with blanks in the other rows. Now you can use a similar expression to earlier to compare them.
=Max(Fields!SOP_PLUS.Value) / Max(Fields!SOP_MINUS.Value)
Keep in mind that the Max function applies to the current group scope. When you add in multiple row and column groups to the mix this can get more complicated. If that becomes an issue, I would suggest looking at rewriting the query to provide these values in separate rows to make the report design easier.
WITH table1([sop-], [sop+]) AS (
SELECT 306, -6
UNION ALL
SELECT 606, -14)
SELECT(CAST([sop+] AS DECIMAL(5, 2)) / CAST([sop-] AS DECIMAL(5, 2))) * 100.0 FROM table1;
Returns :
-1.960784000
-2.310231000

How do I calculate the percentage of a count function?

I am trying to take the percentage of a count function so to create a MS BIDS report resembling this excel file:
Excel Close Rate Summary
The unique identifier for the opportunities is the field "opportunityid", so I am using COUNT(Fields!opportunityid.Value) to determine the number of cases in each stage. I want to write an expression that will return the percentage of cases in each stage per creation month. Which can be seen in the above excel screenshot.
This is my current MS BIDS report when i preview it
To be more specific, I want to have the percentage of "Active" and "New" opportunities in January to represent 67% and 33% respectively. 67% comes from 4/6. The 4 comes from the active opportunities out of the 6 opportunities created in January. Likewise, the 33% comes from the 2 new opportunities out of the 6 that were created in January.
There are more stage names than Active and New. Other options include New, Warm, Hot, Implementation, Active, Hibernate or Canceled. This is relevant to mention because I have tried to create an expression that counts based on the number of opportunities with a specific stage name, but have been unsuccessful.
Currently the expression I am using to calculate the percentage is:
=COUNT(Fields!new_rptstage.Value)/SUM(COUNT(Fields!opportunityid.Value),"GroupbyStageName")
Based on this expression, I am only able to get 1/1 or 100% for each of the stage names. I have tried a bunch of variations of the above expression by changing the scope, but have been unsuccessful in getting the desired results. Can someone explain how to correct this?
SAMPLE DATA:
In the sample data, I want the expression to be in the percentage column. The percentage should be the # of cases in a particular stage for the total cases that month. So looking at the above picture:
Active February 54 54/168 [have 54/168 display as a percentage]
Warm February 8 8/168
etc.
EDIT:
These are the expressions that may help show the underlying data in the chart.
The creation month expression is
=Fields!MonthCreated.Value & " " & year(Fields!createdon.Value)
The percent expression is listed above.
You don't want to use the COUNT() function. COUNT(*) returns a count of the number of rows that have a value. It doesn't return the actual value.
Since you've only showed a screen shot of your report, I don't know how your underlying data columns relate to it, but what you want to do for your Percent column expression is this:
This is psuedo code because I don't know your dataset field names:
CaseCount.Value / SUM(CaseCount.Value)
EDIT: Now that I better understand how your data relates to your report, I think the only change you need to make to your existing formula is casting it to a decimal type. It's probably rounding all fractions up to 1.
Try this for the expression in your percentage column:
=CDbl(COUNT(Fields!new_rptstage.Value))/CDbl(SUM(COUNT(Fields!opportunityid.Value),"GroupbyStageName"))

Resources