前年の利益を特定の年の週まで表示する列を作成する必要があります。したがって、現在の年を週に分割し、特定の週の利益を示します。より明確にするために、前年の利益が 1000 だったとしましょう。今年の最初の週の利益は 100、2 番目の週は 200、3 番目は -100 (損失) などです。したがって、次のようになります。
week1|week2|week3|
1100 |1300 |1200 |
私が試したのは:
SELECT
CASE when f1.year = DATE_PART('year', now()) THEN f1.week END as week,
profit as profit
FROM (
SELECT
DATE_PART('week', so.date_order) as week,
DATE_PART('year', so.date_order) as year,
so.profit as profit
FROM
sale_order as so
GROUP BY
week, year, profit
WHERE
so.date_order >= date_trunc('year', now() - '1 year'::interval)::timestamp::date and so.date_order <= date_trunc('year', now()+ '1 year'::interval)::timestamp::date-1
)as f1
GROUP BY
week, profit
ORDER BY
week
しかし、これは必要に応じて機能していません。これは、特定の週ごとに利益を分割するためです。つまり、その週の利益のみが表示されますが、「その週の利益」+「前年度の利益」が必要です。
ウィンドウ関数を試す私のクエリ:
(
SELECT
x.id as id,week as week, x.last_year_profit + y.running_profit as week_profit
FROM
(
SELECT
min(sol.id) as id,
--DATE_PART('year', so.date_order) AS calcyear, DATE_PART('week', so.date_order) AS calcweek,
sum(sol.price_subtotal - (CASE WHEN sol.account_cost_amount != 0 THEN sol.account_cost_amount ELSE sol.purchase_price END )) as last_year_profit
-- sum(sol.price_subtotal) as price_unit, sum(sol.purchase_price) as purchase_price, sum(sol.account_cost_amount) as account_cost_amount
FROM
sale_order as so
INNER JOIN sale_order_line as sol ON (sol.order_id = so.id)
INNER JOIN res_partner as rp ON (so.partner_id = rp.id)
WHERE EXISTS (
SELECT * FROM res_partner_category_rel rpcl
WHERE
rpcl.partner_id=rp.id and rpcl.category_id=37
and (so.date_order >= date_trunc('year', now() - '1 year'::interval)::timestamp::date and so.date_order <= date_trunc('year', now())::timestamp::date-1 )
and so.state != 'cancel'
)
) as x
CROSS JOIN (
SELECT
date_trunc('week', so.date_order) as week,
sum(sum(sol.price_subtotal - (CASE WHEN sol.account_cost_amount != 0 THEN sol.account_cost_amount ELSE sol.purchase_price END ))) OVER ( ORDER BY date_trunc('week', so.date_order)) as running_profit
FROM
sale_order as so
INNER JOIN sale_order_line as sol ON (sol.order_id = so.id)
INNER JOIN res_partner as rp ON (so.partner_id = rp.id)
WHERE EXISTS (
SELECT * FROM res_partner_category_rel rpcl
WHERE
rpcl.partner_id=rp.id and rpcl.category_id=37
AND so.date_order >= date_trunc('year', now())::timestamp::date
AND so.date_order < date_trunc('year', now() + '1 year'::interval)::timestamp::date
and so.state != 'cancel'
)
GROUP BY
week
) as y
GROUP BY
id, week,week_profit
) as f1
何らかの理由で利益を週に分割せず、次のように 1 つの行の合計のみを表示します。
week |week_profit|
20130114| 1500 |