Den oprindelige forespørgsel giver allerede de grundlæggende detaljer pr. dag for hver bruger. Det er ikke nødvendigt at revidere den beregning. Pak blot forespørgslen ind i et CTE-udtryk.
Her er kolonnerne produceret af den oprindelige forespørgsel:
| date | profit | user_id | amount | percent | total_inv | user_profit |
Det er ikke klart, hvad du vil med procent. Jeg tror ikke, at man let kan aggregeres, hvis man husker, hvad den værdi repræsenterer.
Noget som dette (med total_share):
WITH query1 AS (
SELECT s.date, s.profit
, i.user_id, i.amount, i.percent
, SUM(i.amount) OVER (PARTITION BY s.date) AS total_inv
, ROUND(s.profit * (i.percent / 100.0) * i.amount / SUM(i.amount) OVER (PARTITION BY s.date), 2) AS user_profit
, ROUND((1.0 * i.amount / (SUM(i.amount) over (partition by s.date))) * i.percent, 2) AS user_share
FROM daily_stats AS s
JOIN investments AS i
ON s.date BETWEEN i.start_date AND i.end_date
WHERE s.date BETWEEN '2021-02-01' AND '2021-02-05'
)
SELECT date
, MAX(profit) AS profit
, MAX(total_inv) AS total_inv
, SUM(user_profit) AS total_profit
, SUM(user_share) AS total_share
FROM query1
WHERE user_id IN (1, 4)
GROUP BY date
;
Med resultat fra violin:
Working test case:Test case med PG V3
Opdaterede din testcase her:Din testcase opdateret