aboutsummaryrefslogtreecommitdiff
path: root/res/sql/views/pg_sales.sql
diff options
context:
space:
mode:
Diffstat (limited to 'res/sql/views/pg_sales.sql')
-rw-r--r--res/sql/views/pg_sales.sql32
1 files changed, 32 insertions, 0 deletions
diff --git a/res/sql/views/pg_sales.sql b/res/sql/views/pg_sales.sql
new file mode 100644
index 0000000..f36d8e7
--- /dev/null
+++ b/res/sql/views/pg_sales.sql
@@ -0,0 +1,32 @@
1CREATE OR REPLACE VIEW sales AS
2
3 SELECT
4 items.uuid AS item_uuid,
5 items.user_uuid AS seller_uuid,
6 items.start_date AS start_date,
7 items.end_date AS end_date,
8 best_bids.uuid AS best_bid_uuid,
9 best_bids.user_uuid AS best_bidder_uuid,
10 best_bids.offer AS best_offer,
11 COALESCE(charges.fee, 0) + COALESCE(charges.rate, 0) * best_bids.offer AS charges
12
13 FROM items
14
15 LEFT OUTER JOIN (
16 SELECT DISTINCT ON (item_uuid) *
17 FROM bids
18 ORDER BY item_uuid, offer DESC
19 ) best_bids
20 ON best_bids.item_uuid = items.uuid
21
22 LEFT OUTER JOIN (
23 SELECT
24 start_date,
25 end_date,
26 SUM(fee) AS fee,
27 SUM(rate) AS rate
28
29 FROM charges
30 GROUP BY charges.start_date, charges.end_date
31 ) charges
32 ON items.end_date BETWEEN charges.start_date AND charges.end_date;