Skip to content
Advertisement

TSQL query with aggregated data

I have a query that returns the min, max, avg and total for two different products. The client however wants the min, max, avg and total combined for both products. However I have an undesired result returned when I try to sum the two products and try to aggregate the date.

The following SQL query returns the individual data for both product:

I then modified the query to the following:

However when I run the second query the results don’t add up. As an example Minimum does not add up to the first query Minimum1 + Minimum2

Advertisement

Answer

I understand that you are storing each product in a different column in the same table. The logic to compute the combined minimum, average and maximum might be as follows :

Meaning :

  • minimum is the lowest value between the minimum of product 1 and the minimum of product 2
  • maximum is the highest value between the maximum of product 1 and the maximum of product 2
  • average is the average of the average of product 1 and the average of product 2
  • total is the sum of both queries

You can adapt these rules as needed according to your requiremens (which you did not fully specified).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement