我有SELECT:
SELECT month, year, ROUND(AVG(q_overall) OVER (rows BETWEEN 10000 preceding and current row),2) as avg
FROM (
SELECT EXTRACT(Month FROM date) as month, EXTRACT(Year FROM date) as year, ROUND(AVG(q_overall),1) as q_overall
FROM fb_parsed
WHERE business_id = 1
GROUP BY year, month
ORDER BY year, month) a
输出:
month year avg
-----------------
12 2012 5
1 2013 4.5
2 2013 4.1
4 2013 4.8
5 2013 4.7
我必须在附表中附上缺失值(在本例中为2013年的第3个月)。平均值必须与前一行相同,这意味着我需要将此表附加到:
3 2013 4.1
我可以使用SELF JOINS和generate_series,还是使用某些UNION选择?
答案 0 :(得分:1)
您可以简化选择。它不需要子查询:
SELECT EXTRACT(Month FROM date) as month,
EXTRACT(Year FROM date) as year,
ROUND(AVG(q_overall), 1) as q_overall,
ROUND(AVG(AVG(q_overall)) OVER (rows BETWEEN 10000 preceding and current row), 2)
FROM fb_parsed
WHERE business_id = 1
GROUP BY year, month;
Windows功能需要order by
。我假设你真的打算:
SELECT EXTRACT(Month FROM date) as month,
EXTRACT(Year FROM date) as year,
ROUND(AVG(q_overall), 1) as q_overall,
ROUND(AVG(AVG(q_overall)) OVER (ORDER BY year, month)), 2)
FROM fb_parsed
WHERE business_id = 1
GROUP BY year, month;
然后,要填写值,您可以使用generate_series()
:
SELECT EXTRACT(Month FROM ym.date) as month,
EXTRACT(Year FROM ym.date) as year,
ROUND(AVG(AVG(q_overall)) OVER (ORDER BY year, month)), 2)
FROM (SELECT generate_series(date_trunc('month', min(date)),
date_trunc('month', max(date)),
interval '1 month') as date
FROM fb_parsed
) ym LEFT JOIN
fb_parsed p
ON EXTRACT(year FROM ym.date) = EXTRACT(year FROM p.date) AND
EXTRACT(month FROM ym.date) = EXTRACT(month FROM p.date) AND
p.business_id = 1
GROUP BY year, month;
我认为这会做你想要的。
答案 1 :(得分:0)
我可以使用SELF JOINS和generate_series吗?
是的,您已关闭,但您当前的查询会产生累积平均值。棘手的部分是用前一个值填补空白(如果PostgreSQL支持IGNORE NULLS
的{{1}}选项,这会更容易......)
LAST_VALUE
编辑:
哎呀,这太复杂了,问题是累积平均值然后NULL不会改变结果而且填补空白
答案 2 :(得分:0)
最终查询:
update products
set sales_tax = buyPrice * 0.08
where sales_tax is null;