I have the following tables in SQLite.
CREATE TABLE IF NOT EXISTS "payouts" (
"id" INTEGER NOT NULL UNIQUE,
"amount" TEXT NOT NULL);
CREATE TABLE "orders" (
"id" INTEGER NOT NULL UNIQUE,
"number" TEXT NOT NULL UNIQUE,
"amount" TEXT NOT NULL,
"fees" REAL NOT NULL,
"payout_id" INTEGER NOT NULL);
CREATE TABLE "tax" (
"rate" TEXT NOT NULL,
"amount" REAL NOT NULL,
"tax" REAL NOT NULL,
"order_id" INTEGER NOT NULL);
INSERT INTO payouts VALUES (1, 97.43)
INSERT INTO orders VALUES (1, "01", 30, 5, 1)
INSERT INTO orders VALUES (2, "02", 80, 5, 1)
INSERT INTO tax VALUES (0.1, 20, 1.82, 1)
INSERT INTO tax VALUES (0.15, 10, 1.30, 1)
INSERT INTO tax VALUES (0.1, 50, 4.55, 2)
INSERT INTO tax VALUES (0.2, 30, 5.00, 2)
I would like a query which returns the following table where the rates are variable and new rates can be added at any time (so the columns of this table change depending on the input).
payout_id | amount_0.1 | amount_0.15 | amount_0.2 | fees | payout_amount |
---|---|---|---|---|---|
1 | 70 | 10 | 30 | 12.57 | 97.43 |
I have some control over the ETL, but if possible I would rather not touch the schema.
I currently have the following but am stuck trying to pivot the result of this appropriately.
SELECT payout_id, rate, SUM(fees) AS fees, SUM(amount) AS amount
FROM (
SELECT * FROM orders
JOIN tax ON orders.id = tax.order_id
);
WHERE payout_id = 1
GROUP BY payout_id, rate