티스토리 뷰

AI/SQL

[SQL] capital gain loss

brave_sol 2024. 12. 26. 12:09
리트코드 Curated SQL 70 중 Medium 

 

1) case이용

select stock_name,
    sum(case 
            when operation = "BUY" then -price
            else price
        end
    ) as capital_gain_loss
from Stocks
group by stock_name

 

2) self join 이용

with grouped as (select stock_name, operation, sum(price) as price
                from Stocks
                group by stock_name, operation
                order by stock_name, operation)

select a.stock_name, 
    (a.price - b.price) as capital_gain_loss
from grouped a
join grouped b
on a.stock_name = b.stock_name
and (a.operation = "Sell" and b.operation = "Buy")
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함