I have a DB Table with a date and a field called posneg, t开发者_开发百科he value is either 'pos', 'neu' or 'neg'.
I need a result set where the posneg values are added and then grouped by date. Like this
2010-10-03 5 (on that date it could be 12 pos, 5 neu and 7 neg)
2010-10-04 -3 (on that date maybe 10 pos, 2 neu and 13 neg)
...and so on
Basically the neu doesn't matter, as you see.
SELECT
date,
posneg = SUM(
CASE posneg
WHEN 'pos' THEN 1
WHEN 'neg' THEN -1
ELSE 0
END
)
FROM atable
GROUP BY date
Try this:
SELECT date, SUM(IF(posneg='pos',1,IF(posneg='neg',-1,0))) as total
FROM table GROUP BY date
with tab as(
select cast('12/12/2010' as smalldatetime) as dt, 'neg' as posneg
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg
union all
select cast('12/15/2010' as smalldatetime) as dt, 'pos' as posneg
)
select dt,
sum(case when posneg='pos' then 1
when posneg='neg' then -1
else 0 end) as total
from tab
group by dt
精彩评论