mysql summation with condition on individual rows -
i have table 3 fields (of relevance question). 1 field numeric, other 2 have text-based content. want sum of numeric field follows:
- group field a
- if field b equal x, add
if field b equal y, subtract
abc, x, 25
abc, x, 15
abc, y, 10
def, x, 20
def, y, 5
the above data return:
abc, 30 def, 15
my query, ideally, produce equivalent of following following:
select fielda, sum(fieldc) sum1 my_table fieldb = 'x' group fielda select fielda, sum(fieldc) sum2 my_table fieldb = 'y' group fielda result = sum1 - sum2
how can in single query?
something should work:
select fielda, sum(case when fieldb = 'x' fieldc else -fieldc end) result my_table group fielda
Comments
Post a Comment