Open positions by user

conditional logic

Open positions by user

Robinhood SQL Interview Question

Robinhood's portfolio page shows how many shares of each stock a user still holds, based on their buy and sell trades.

For each user_id and symbol, find the shares bought minus the shares sold as net_shares. Only return positions where the user still holds more than 0 shares. Sort by user_id, then by symbol.

Asked of

  • Data Analyst
  • Business Analyst
  • BI Analyst
  • Product Analyst
  • Analytics Engineer

tradesTable18 rows

Column NameType
trade_idBIGINT
user_idBIGINT
symbolVARCHAR
sideVARCHAR
sharesBIGINT
priceDOUBLE
executed_atTIMESTAMP

tradesExample Input

trade_iduser_idsymbolsidesharespriceexecuted_at
61001801AAPLbuy10185.22024-01-04 09:35:12
61002802TSLAbuy5238.452024-01-09 10:02:44
61003801NVDAbuy2495.12024-01-22 13:15:05
61004803AMZNbuy8151.32024-01-30 15:42:18
61005802TSLAsell5187.92024-02-06 09:48:31
61006804AAPLbuy3188.852024-02-13 11:21:09
61007801AAPLsell4182.32024-02-20 14:05:57
61008803NVDAbuy1721.332024-02-27 10:30:00
61009805AMZNbuy12175.12024-03-01 09:31:40
61010804TSLAbuy6199.42024-03-08 12:44:23
61011802NVDAbuy2875.282024-03-14 15:10:11
61012805AAPLsell2172.622024-03-21 13:55:02
61013801NVDAsell2903.562024-03-28 09:59:48
61014803AMZNsell8180.972024-04-02 10:12:30
61015804AAPLbuy5169.612024-04-10 11:47:16
61016806TSLAbuy10162.52024-04-16 14:22:05
61017805NVDAbuy1846.712024-04-23 09:40:59
61018802AMZNbuy4179.622024-04-30 15:58:21

Example Output

user_idsymbolnet_shares
801AAPL6
802AMZN4
802NVDA2
803NVDA1
804AAPL8
804TSLA6
805AMZN12
805NVDA1
806TSLA10

Explanation

User 801 bought 10 AAPL shares and sold 4, so 6 are left. They also bought and sold 2 NVDA shares, which leaves 0, so that position is not shown. User 805 sold 2 AAPL shares with no matching buy in the data, which leaves -2, so it is not shown either.

The example above is a small slice of the data. Your query runs against the full tables.