I have a question. If I am given a table with positive and negative numbers and I want to find total of all positives and total of all negatives separately and display it in one line. I was able to come up with one solution (below). I wanted to check if it is possible to have a better solution using Select and CASE statement
id amount
1 100
2 -10
3 50
4 -80
5 20
6 -20
positive negative
170 -110
My Solution:
create table #temp (id int, amount int)
insert into #temp values (1, 100)
insert into #temp values (2, -10)
insert into #temp values (3, 50)
insert into #temp values (4, -80)
insert into #temp values (5, 20)
insert into #temp values (6, -20)
with positive as
(select sum(amount) as posNum from temp where amount > 0)
, negative as
(select sum(amount) as negNum from temp where amount < 0)
select *, (select * from negative) from positive
Use conditional aggregation: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=e2fa9cc6aee27cc501c9cda98bc2cf2d
SELECT
SUM(CASE WHEN amount > 0 THEN amount END) AS positive,
SUM(CASE WHEN amount < 0 THEN amount END) AS negative
FROM #temp;
Output:
positive negetive
170 -110
You can also use sign()
to determine it is positive or negative number
select sum(case when sign(amount) = 1 then amount end),
sum(case when sign(amount) = -1 then amount end)
from #temp
This will work:
1) For SQL Server
SELECT
SUM(IIF(amount > 0, amount, 0)) positive,
SUM(IIF(amount < 0, amount, 0)) negative
FROM TABLENAME;
2) For SQL Server and MySQL
SELECT
SUM(CASE WHEN amount > 0 THEN amount END) positive,
SUM(CASE WHEN amount < 0 THEN amount END) negative
FROM TABLENAME;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.