Search code examples
sqlsql-servervisual-studioreporting-servicesfetchxml

How to get 2 aggregate functions in one FetchXML script?


Let's say I have a dataset:

+--------+-------+----------+
| Animal | Price | FoodCost |
+--------+-------+----------+
|      1 |    23 |       22 |
|      1 |    32 |       33 |
|      1 |     7 |       69 |
|      2 |    45 |       55 |
|      2 |   432 |       82 |
|      2 |    33 |       34 |
|      3 |    67 |       44 |
|      5 |   671 |       62 |
|      8 |   234 |       43 |
+--------+-------+----------+

The result that I am looking for in my tablix is:

+--------+-------+----------+
| Animal | Price | FoodCost |
+--------+-------+----------+
|      1 |    62 |      124 |
|      2 |   510 |      171 |
|      3 |    67 |       44 |
|      5 |   671 |       62 |
|      8 |   234 |       43 |
+--------+-------+----------+

I understand how to do 1 aggregate, but how would I do 2 aggregates, namely, summing the price and the foodcost for each animal?


Solution

  • SQL:

    select Animal, sum(Price) as Sum_Price, sum(FoodCost)  as sum_foodcost
    from dbo.AggegateTest
    group by Animal
    

    Generated FetchXML: with http://sql2fetchxml.com/

    <fetch aggregate="true" mapping="logical">
      <entity name="AggegateTest">
        <attribute name="Animal" alias="AggegateTest1.Animal" />
        <attribute name="price" alias="Sum_Price" aggregate="sum" />
        <attribute name="foodcost" alias="sum_foodcost" aggregate="sum" />
        <attribute name="Animal" alias="Animal" groupby="true" />
      </entity>
    </fetch>