如何减去一列中有一个匹配值的两行

发布于 2024-12-20 13:20:50 字数 779 浏览 3 评论 0原文

我正在比较不同年份同一周的销售额。就像 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

我想要做的是减去不同年份的相同周,以获得销售额的差异。就像 week2011-week2010 一样,结果应该看起来像这样,

week|year     |difference
 1  |2011-2010|5
 2  |2011-2010|6

我只是不知道如何这样减去:)

I'm comparing sales for same week of different year. Like first week of 2010 and 2011. So with my query I get such results.

week|year|sales
1   |2010|5
1   |2011|10
2   |2010|7
2   |2011|13

My query looks like this:

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

What I want to do, is to subtract same weeks of different years, to get the difference in sales. Like week2011-week2010 and results should look like that

week|year     |difference
 1  |2011-2010|5
 2  |2011-2010|6

I just don't have an idea how to subtract like that:)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

银河中√捞星星 2024-12-27 13:20:50

要获得两年之间的差异,请尝试以下操作:

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

To get the difference between the two years, try this:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文