L.s
L.s

Reputation: 57

SQL querying for segment positive values and negative and sum the value for distinct name

Here is the question below

My querying is as following:

SELECT DISTINCT name, money CASE
         WHEN [money] < 0 THEN SUM(money) GROUP BY name
       END AS "sum_of_withdraws"
       CASE
         WHEN [money] >= 0 THEN SUM(money) GROUP BY name
       END AS "sum_of_deposits"
FROM table

Can anyone show a correct querying or improve my querying?

Upvotes: 0

Views: 163

Answers (2)

Sheriff
Sheriff

Reputation: 868

Find this query...

SELECT 
    [name],
    SUM(CASE WHEN [money] >=0   THEN [Money] else 0 END)    sum_of_deposits,
    SUM(CASE WHEN [money] <0    THEN [Money] else 0 END)*-1 sum_of_withdrawals
FROM 
    transfers
GROUP BY 
    [name]

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270573

I think you want:

SELECT name,
       SUM(CASE WHEN [money] < 0 THEN money
           END) AS sum_of_withdraws,
       SUM(CASE WHEN [money] >= 0 THEN money
           END) AS "sum_of_withdraws"
FROM table
GROUP BY name;

The CASE expression is an argument to SUM(). And GROUP BY is an entirely separate clause that follows FROM.

Upvotes: 1

Related Questions