Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate positive and negative numbers into their own columns?

Tags:

sql

sybase

I have a table with the following columns and data:

activity_dt | activity_amt
 2009-01-01 |   -500
 2009-01-01 |    750

Can I write a query that looks at the sign of activity_amt and puts it in the credits column if it's positive, and the debits column if it's negative? (I'm using Sybase)

activity_dt | debits | credits
 2009-01-01 |  -500  |   750
like image 965
Mike Sickler Avatar asked Nov 09 '09 02:11

Mike Sickler


2 Answers

select activity_dt, 
    sum(case when activity_amt < 0 then activity_amt else 0 end) as debits, 
    sum(case when activity_amt > 0 then activity_amt else 0 end) as credits
from the_table
group by activity_dt
order by activity_dt
like image 62
schinazi Avatar answered Sep 30 '22 21:09

schinazi


I'm not sure about the exact syntax in Sybase, but you should be able to group on the date and sum up the positive and negative values:

select
  activity_dt,
  sum(case when activity_amt < 0 then activity_amt else 0 end) as debits,
  sum(case when activity_amt >= 0 then activity_amt else 0 end) as credits
from
  theTable
group by
  activity_dt
like image 43
Guffa Avatar answered Sep 30 '22 19:09

Guffa