# 如何减去两行中具有匹配值的两行How to Subtract Two Rows which Have One Matching Value in a Column

``````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
``````

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

## 1 个回复1

### ===============>>#1 票数：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
``````

2回复

3回复

1回复

1回复

2回复

1回复

1回复

1回复

1回复

1回复