前 3 个月的值总和
Posted
技术标签:
【中文标题】前 3 个月的值总和【英文标题】:Sum of values from 3rd previous month 【发布时间】:2015-02-20 18:53:09 【问题描述】:我很难从 12 月开始抓取行(从上个月第 3 个月开始)。我正在尝试计算特定时间段内售出的产品数量。这是我当前的查询:
SELECT
a.id,
a.default_code,
(
SELECT SUM(product_uom_qty)
AS
"Total Sold"
FROM
sale_order_line c
WHERE
c.product_id = a.id
),
(
SELECT SUM(product_uom_qty)
AS
"Month 3"
FROM sale_order_line c
WHERE
c.product_id = a.id
AND
MONTH(c.create_date) = MONTH(CURRENT_DATE - INTERVAL '3 Months')
AND
YEAR(c.create_date) = YEAR(CURRENT_DATE - INTERVAL '3 Months')
)
FROM
product_product a
这就是数据库的样子:
sale_order_line
product_id product_uom_qty create_date
33 230 2014-07-01 16:47:45.294313
product_product
id default_code
33 WHDXEB33
这是我收到的错误:
ERROR: function month(timestamp without time zone) does not exist LINE 21: MONTH(c.create_date) = MONTH(CURRENT_DATE - INTERVAL
任何帮助指出我正确的方向?
【问题讨论】:
您的查询有什么问题? 嗨伦纳特。抱歉,我已经添加了上面的错误。 【参考方案1】:使用date_trunc() 计算时间戳范围:
SELECT id, default_code
, (SELECT SUM(product_uom_qty)
FROM sale_order_line c
WHERE c.product_id = a.id
) AS "Total Sold"
, (SELECT SUM(product_uom_qty)
FROM sale_order_line c
WHERE c.product_id = a.id
AND c.create_date >= date_trunc('month', now()) - interval '2 month'
AND c.create_date < date_trunc('month', now()) - interval '1 month'
) AS "Month 3"
FROM product_product a;
要获得十二月(现在是二月),请使用以下表达式:
AND c.create_date >= date_trunc('month', now()) - interval '2 month'
AND c.create_date < date_trunc('month', now()) - interval '1 month'
date_trunc('month', now())
产生“2015-02-01 00:00”,减去 2 个月后,得到“2014-12-01 00:00”。因此,“3 个月”可能具有欺骗性。
此外,请务必使用 sargable 表达式,如演示以获得更快的性能并允许使用索引。
替代品
根据您的实际数据库设计和数据分布,这可能会更快:
SELECT a.id, a.default_code, c."Total Sold", c."Month 3"
FROM product_product a
LEFT JOIN (
SELECT product_id AS id
, SUM(product_uom_qty) AS "Total Sold"
, SUM(CASE WHEN c.create_date >= date_trunc('month', now()) - interval '2 month'
AND c.create_date < date_trunc('month', now()) - interval '1 month'
THEN product_uom_qty ELSE 0 END) AS "Month 3"
FROM sale_order_line
GROUP BY 1
) c USING (id);
由于您要选择所有行,这可能比相关子查询更快。在加入的同时,在加入之前进行汇总,这样更便宜。 选择单个或少数产品时,这可能实际上是较慢 em>!比较:
Aggregate a single column in query with many columns Optimize GROUP BY query to retrieve latest record per user或者使用 Postgres 中的FILTER
子句9.4+:
...
, SUM(product_uom_qty)
FILTER (WHERE c.create_date >= date_trunc('month', now()) - interval '2 month'
AND c.create_date < date_trunc('month', now()) - interval '1 month'
) AS "Month 3"
...
详情:
Select multiple row values into single row with multi-table clauses【讨论】:
【参考方案2】:这将避免代价高昂的关联子查询
select
pp.id, pp.default_code,
sum(sol.product_uom_qty) as "Total Sold",
sum((
date_trunc('month', pp.create_date) =
date_trunc('month', current_date) - interval '3 months'
)::int * sol.product_uom_qty
) as "Month 3"
from
product_product pp
left join
sale_order_line sol on pp.id = sol.product_id
group by 1, 2
boolean
到 integer
的强制转换得到 0 或 1,方便乘以要相加的值
【讨论】:
以上是关于前 3 个月的值总和的主要内容,如果未能解决你的问题,请参考以下文章