Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of the grouped distinct values

This is a bit hard to explain in words ... I'm trying to calculate a sum of grouped distinct values in a matrix. Let's say I have the following data returned by a SQL query:

------------------------------------------------
| Group | ParentID | ChildID | ParentProdCount |
|     A |        1 |       1 |               2 |
|     A |        1 |       2 |               2 |
|     A |        1 |       3 |               2 |
|     A |        1 |       4 |               2 |
|     A |        2 |       5 |               3 |
|     A |        2 |       6 |               3 |
|     A |        2 |       7 |               3 |
|     A |        2 |       8 |               3 |
|     B |        3 |       9 |               1 |
|     B |        3 |      10 |               1 |
|     B |        3 |      11 |               1 |
------------------------------------------------

There's some other data in the query, but it's irrelevant. ParentProdCount is specific to the ParentID.

Now, I have a matrix in the MS Report Designer in which I'm trying to calculate a sum for ParentProdCount (grouped by "Group"). If I just add the expression

=Sum(Fields!ParentProdCount.Value)

I get a result 20 for Group A and 3 for Group B, which is incorrect. The correct values should be 5 for group A and 1 for group B. This wouldn't happen if there wasn't ChildID involved, but I have to use some other child-specific data in the same matrix.

I tried to nest FIRST() and SUM() aggregate functions but apparently it's not possible to have nested aggregation functions, even when they have scopes defined.

I'm pretty sure there is some way to calculate the grouped distinct sum without needing to create another SQL query. Anyone got an idea how to do that?

like image 507
miq Avatar asked Oct 24 '11 14:10

miq


1 Answers

Ok I got this sorted out by adding a ROW_NUMBER() function my SQL query:

SELECT Group, ParentID, ROW_NUMBER() OVER (PARTITION BY ParentID ORDER BY ChildID ASC) AS Position, ChildID, ParentProdCount FROM Table

and then I replaced the SSRS SUM function with

=SUM(IIF(Position = 1, ParentProdCount.Value, 0))
like image 102
miq Avatar answered Sep 28 '22 04:09

miq