我需要制作一个专栏来显示前一年的利润,直到给定的一周。因此,它将以周为单位划分当前年份,并显示给定周的利润是多少。为了更清楚,假设上一年的利润是 1000。今年第一周的利润是 100,第二周的利润是 200,三分之二,周 -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
由于某种原因,它不会在几周内拆分利润,而是只显示一行总计,如下所示:
week |week_profit|
20130114| 1500 |