aboutsummaryrefslogtreecommitdiff
path: root/res/sql/views/orcl_accounts.sql
blob: f3f5d6e2c1c01c006f3f5d6e494f2cc85a5b927a (plain)
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
32
CREATE OR REPLACE VIEW accounts AS

  SELECT
    users.uuid                                                       AS user_uuid,
    users.username                                                   AS username,
    COALESCE(transactions.balance, 0)                                AS balance,
    COALESCE(sales.open_bids, 0)                                     AS open_bids,
    COALESCE(transactions.balance, 0) - COALESCE(sales.open_bids, 0) AS equity

  FROM users

    LEFT OUTER JOIN (
                      SELECT
                        user_uuid,
                        SUM(transactions.amount) AS balance

                      FROM transactions
                      WHERE transaction_date < current_datetime()
                      GROUP BY user_uuid
                    ) transactions
      ON transactions.user_uuid = users.uuid

    LEFT OUTER JOIN (
                      SELECT
                        best_bidder_uuid,
                        SUM(sales.best_offer + sales.charges) AS open_bids

                      FROM sales
                      WHERE end_date > current_datetime()
                      GROUP BY best_bidder_uuid
                    ) sales
      ON sales.best_bidder_uuid = users.uuid;