domfitty domfitty - 2 months ago 13
MySQL Question

MYSQL: Sum rows with a particular value

I've got a table with many rows that contains different type of values.
Every row has a 2 column:

FieldName
and
FieldValue
and I need to sum all rows of counter type

SELECT FieldValue as somma FROM `my_values` as value WHERE value.`FieldName` ='counter'


I tried this query

select sum(value.somma) as a from (
SELECT FieldValue as somma FROM `my_values` as value WHERE value.`FieldName` ='counter'
)


But I have the following error:


#1248 - Every derived table must have its own alias

Answer

You should use a simple sum()

SELECT sum(FieldValue) as somma 
FROM `my_values`
WHERE FieldName` ='counter'

or if you need using alias then prefix the column in proper way

SELECT sum(value.FieldValue) as somma 
FROM `my_values` as value WHERE value.`FieldName` ='counter'