我正在使用postgres 9.3。而且我没有太多关于跑步总数的曝光
我有一项要求,即我需要每年生成一份报告,其中包含客户在特定年份首次订购之前或之后的平均六个月支出。
以下是架构:
CREATE TABLE orders
(
persistent_key_str character varying,
ord_id character varying(50),
ord_submitted_date date,
item_sku_id character varying(50),
item_extended_actual_price_amt numeric(18,2)
);
INSERT INTO orders VALUES ('01120736182','ORD6266073','2010-12-08','100856-01',39.90);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','100265-01',49.99);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','200020-01',29.99);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','100817-01',44.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200251-01',79.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200269-01',59.99);
INSERT INTO orders VALUES('01011679971','ORD89332495','2012-12-05','200102-01',169.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','100907-01',89.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200840-01',129.99);
INSERT INTO orders VALUES('01120736182','ORD125155068','2013-07-27','201443-01',199.99);
INSERT INTO orders VALUES('01120736182','ORD167230815','2014-06-05','200141-01',59.99);
INSERT INTO orders VALUES('01011679971','ORD174927624','2014-08-16','201395-01',89.99);
这是我:
WITH year_cte
as
(
SELECT EXTRACT(YEAR FROM ord_submitted_date) ord_year, ord_id, ord_submitted_date from ORDERS
)
SELECT --persistent_key_str
c.ord_year
--, ord_id
, AVG(AVG(o.item_extended_actual_price_amt)) OVER(PARTITION BY c.ord_year) Avg_6_month_spend
FROM orders o INNER JOIN year_cte c ON c.ord_id = o.ord_id
WHERE o.ord_submitted_date between (c.ord_submitted_date - interval '365 days')::date and c.ord_submitted_date
group by o.ord_submitted_date, o.item_extended_actual_price_amt, c.ord_year
Here is a SQLFiddle with the above
我非常感谢你在任务中提供一些指导。
我希望看到这样的事情。 “Ord_year”,“平均6个月花费”
2010, 1645.39,
2011, 255.94,
2012, 247.53,
2013, 230.36,
2014, 239.82,
答案 0 :(得分:0)
尝试此查询:
SELECT q.year, avg( o.item_extended_actual_price_amt )
FROM (
SELECT EXTRACT(YEAR FROM ord_submitted_date) as year,
min( ord_submitted_date ) as first_order_date
FROM ORDERS
GROUP BY year
) q
JOIN ORDERS o
ON o.ord_submitted_date
BETWEEN q.first_order_date - INTERVAL '6 months'
AND q.first_order_date + INTERVAL '6 months'
GROUP BY q.year
ORDER BY q.year
;