summaryrefslogtreecommitdiffstats
path: root/sql/views.sql
blob: 8edfa9fcbda5e4ad0bd2515d5fd8e26730de8a73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
BEGIN TRANSACTION;
CREATE VIEW IF NOT EXISTS purchaseprices AS SELECT product, SUM(price * amount) / SUM(amount) AS price FROM restock GROUP BY product;
CREATE VIEW IF NOT EXISTS invoice AS 
	SELECT user, timestamp, id AS productid, name AS productname,
		CASE
			WHEN user < 0 THEN
				(SELECT price
					FROM purchaseprices
					WHERE purchaseprices.product = id)
			else
				(SELECT
					CASE
						WHEN user=0 THEN guestprice
						else memberprice
					END
					FROM prices
					WHERE product = id AND valid_from <= timestamp
					ORDER BY valid_from DESC LIMIT 1)
			END AS price
		FROM sales INNER JOIN products ON sales.product = products.id
		ORDER BY timestamp;
COMMIT;