2

I have a DB Table with a date and a field called posneg, the 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.

0

3 Answers 3

3
SELECT
  date,
  posneg = SUM(
    CASE posneg
      WHEN 'pos' THEN 1
      WHEN 'neg' THEN -1
      ELSE 0
    END
  )
FROM atable
GROUP BY date
Sign up to request clarification or add additional context in comments.

1 Comment

Andriy M's answer worked well. Since it was the first one, I tried that first... I rewrote it to: SELECT dateadd(d, 0, datediff(d, 0, date)) as d, posneg = SUM(CASE posneg WHEN 'pos' THEN 1 WHEN 'neg' THEN -1 ELSE 0 END) FROM Table GROUP BY dateadd(d, 0, datediff(d, 0, date)) order by d So thanks a lot :)
0

Try this:

SELECT date, SUM(IF(posneg='pos',1,IF(posneg='neg',-1,0))) as total
FROM table GROUP BY date

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.