Skip to content
Advertisement

Sum data based on columns

Table 1 has several columns with distinct values.

Product,    
Type,   
Sales Amount,   
Value,  
Month,  
Year

What I want is this information combined and condensed to the different column levels, so that the sale and value amounts are sum’d based on the product and type in the year and months instead of each distinct line being displayed as a separate value.

For example if I have all columns being the same but the sale and value have distinct values I would want that to be sum’d together with the rows it corresponded to.

In addition, I want to know my loss ratio between the sale amount and the actual value of the product

Select Product,
Type,
Sale,
Value,
Month,
Year
Cast(value / sale as Dec) AS 'Loss Ratio' 

From Table 1

Some help please?

Advertisement

Answer

Seems like you just need a GROUP BY with SUM.

SELECT Product,
Type,
SUM(Sale) AS Sale,
SUM(Value) AS Value,
Month,
Year,
SUM(Sale)/SUM(Value) AS 'Loss Ratio' 
FROM Table1
GROUP BY Month, Year, Product, Type

SqlFiddle

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