我正在比较不同年份同一周的销售情况。就像2010年和2011年的第一周一样。所以我的查询得到了这样的结果。
week|year|sales
1 |2010|5
1 |2011|10
2 |2010|7
2 |2011|13
我的查询如下:
SELECT
min(x.id) AS id,
week as week,
year,
COUNT(*) AS amount,
SUM(price_unit) AS price
FROM (
SELECT
so.id as id,
DATE_PART('week', so.date_order) AS week,
DATE_PART('year', so.date_order) AS year,
sol.price_unit
FROM
sale_order AS so
INNER JOIN sale_order_line AS sol ON sol.order_id = so.id
WHERE so.date_order BETWEEN '2010-01-01' AND '2011-12-31'
) AS x
GROUP BY
week,
year
我想做的是减去不同年份的同一周,以获得销售差异。就像2011-2011周那样,结果看起来应该是那样的
week|year |difference
1 |2011-2010|5
2 |2011-2010|6
我只是不知道如何减样:)
答案 0 :(得分:1)
要获得两年之间的差异,请尝试以下方法:
SELECT
week as week,
'2011-2010' as year,
sum(case calcyear when 2011 then 1 else -1 end) AS amount,
sum(case calcyear when 2011 then price_unit else -1*price_unit end) AS price
FROM (
SELECT
so.id as id,
DATE_PART('week', so.date_order) AS week,
DATE_PART('year', so.date_order) AS calcyear,
sol.price_unit
FROM
sale_order AS so
INNER JOIN sale_order_line AS sol ON sol.order_id = so.id
WHERE so.date_order BETWEEN '2010-01-01' AND '2011-12-31'
) AS x
GROUP BY
week