[1393_MEDIUM] Capital Gain/Loss

2022. 8. 10. 18:50·SQL/LeetCode
 

Capital Gain/Loss - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Table: Stocks

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| stock_name    | varchar |
| operation     | enum    |
| operation_day | int     |
| price         | int     |
+---------------+---------+
(stock_name, operation_day) is the primary key for this table.
The operation column is an ENUM of type ('Sell', 'Buy')
Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.
It is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day. It is also guaranteed that each 'Buy' operation for a stock has a corresponding 'Sell' operation in an upcoming day.

 

Write an SQL query to report the Capital gain/loss for each stock.

The Capital gain/loss of a stock is the total gain or loss after buying and selling the stock one or many times.

Return the result table in any order.

The query result format is in the following example.

 

# Capital gain? 

: 증권, 선물계약과 옵션 등을 포함한 자본자산의 거래를 통한 매입가격과 매각가격의 차이에 의한 시세 차익을 말함.

 

문제 조건 

- 각 주식에 대해 자본 이득/손실을 출력하시오

- Captial gain/loss? : 주식을 한 번 또는 여러 번 사고 팔은 후의 총 손익. 

 

Example 1:

Input: 
Stocks table:
+---------------+-----------+---------------+--------+
| stock_name    | operation | operation_day | price  |
+---------------+-----------+---------------+--------+
| Leetcode      | Buy       | 1             | 1000   |
| Corona Masks  | Buy       | 2             | 10     |
| Leetcode      | Sell      | 5             | 9000   |
| Handbags      | Buy       | 17            | 30000  |
| Corona Masks  | Sell      | 3             | 1010   |
| Corona Masks  | Buy       | 4             | 1000   |
| Corona Masks  | Sell      | 5             | 500    |
| Corona Masks  | Buy       | 6             | 1000   |
| Handbags      | Sell      | 29            | 7000   |
| Corona Masks  | Sell      | 10            | 10000  |
+---------------+-----------+---------------+--------+
Output: 
+---------------+-------------------+
| stock_name    | capital_gain_loss |
+---------------+-------------------+
| Corona Masks  | 9500              |
| Leetcode      | 8000              |
| Handbags      | -23000            |
+---------------+-------------------+
Explanation: 
Leetcode stock was bought at day 1 for 1000$ and was sold at day 5 for 9000$. Capital gain = 9000 - 1000 = 8000$.
Handbags stock was bought at day 17 for 30000$ and was sold at day 29 for 7000$. Capital loss = 7000 - 30000 = -23000$.
Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$. It was bought again at day 4 for 1000$ and was sold at day 5 for 500$. At last, it was bought at day 6 for 1000$ and was sold at day 10 for 10000$. Capital gain/loss is the sum of capital gains/losses for each ('Buy' --> 'Sell') operation = (1010 - 10) + (500 - 1000) + (10000 - 1000) = 1000 - 500 + 9000 = 9500$.

 

문제 풀이 

select stock_name
        , sum(case when operation = 'Sell' then price end) - sum(case when operation = 'Buy' then price end) as capital_gain_loss
from stocks 
group by stock_name

 

 

저작자표시 (새창열림)

'SQL > LeetCode' 카테고리의 다른 글

[2329#_EASY] Product Sales Analysis V  (0) 2022.08.10
[1398#_MEDIUM] Customers Who Bought Products A and B but Not C  (0) 2022.08.10
[2082#_EASY] The Number of Rich Customers  (0) 2022.08.10
[2072#_EASY] The Winner University  (0) 2022.08.10
[2026#_EASY] Low-Quality Problems  (0) 2022.08.10
'SQL/LeetCode' 카테고리의 다른 글
  • [2329#_EASY] Product Sales Analysis V
  • [1398#_MEDIUM] Customers Who Bought Products A and B but Not C
  • [2082#_EASY] The Number of Rich Customers
  • [2072#_EASY] The Winner University
소금깨
소금깨
  • 소금깨
    고군분투 인생살이
    소금깨
  • 전체
    오늘
    어제
    • 분류 전체보기 (328)
      • SQL (271)
        • 프로그래머스 (27)
        • LeetCode (198)
        • Hacker Rank (27)
        • Solve SQL (1)
        • 개념 (15)
      • 데이터 분석 (16)
        • 참고하며 공부하기 (14)
      • 기타 (15)
        • 통계 (14)
      • 오류 (6)
      • 인생살이 (0)
        • 리뷰 (0)
        • 일기 (0)
      • 中文 (0)
      • TABLEAU (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    HACKER_RANK
    group by
    직장인인강
    medium
    패캠챌린지
    해커랭크
    프로그래머스
    MySQL
    파이썬을활용한시계열데이터분석AtoZ올인원패키지Online
    패스트캠퍼스후기
    파이썬을활용한시계열데이터분석
    easy
    SQL
    직장인자기계발
    solvesql
    패스트캠퍼스
    프리미엄
    LeetCode
    시계열데이터분석
    Hard
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
소금깨
[1393_MEDIUM] Capital Gain/Loss
상단으로

티스토리툴바