tags:

views:

42

answers:

3

I want to find the SUM of values in a column weight. I want this sum for all records that are identified with a common value in one of the columns name. Further, I want to consider only those records that have a certain value in the column type.

name weight type
1 $ 12.00 A
2 $ 7.00 B
2 $ 7.00 A
1 $ 1.00 C
2 $ 7.00 B
1 $ 1.00 C
2 $ 7.00 B
1 $ 7.00 B
2 $ 7.00 C
2 $ 7.00 B

I want the total weight for name 2, for the types A and B. Can a subquery be written for this or only looping can be done. Tnx.

+4  A: 
SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = @name
AND
    Type = @type

Or to be specific for your request

SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = '2'
AND
    Type IN('A', 'B')

However, if it is purely a single value you are after for your filter then you can just SUM with a WHERE clause.

SELECT
    SUM(Weight)
FROM
    MyTable
WHERE
    Name = '2'
AND
    Type IN('A', 'B')
Robin Day
thanks. It seems a lot simpler now...
+1  A: 

This will show you the sum of weights for each name, where the type is A or B:

select name, sum(weight) as WeightSum
from MyTable t
where type in ('A', 'B')
group by name
RedFilter
wow. thanks for the quick post.
+1  A: 

this really depends on ones interpretation of the OPs question, which is a little vague to me. But give this a try:

SELECT
    SUM(Weight)
    FROM MyTable
    WHERE Name=2 AND Type IN ('A','B','C')
KM