SQL 列包含一年的结果,另一列包含另一年的结果

SQL Column with results from a year and other column with results from another year

自从我使用 SQL 以来已经有一段时间了,所以我可能会被堆放在一些非常简单的东西中,但这里是这样的:

我将通过示例数据向您展示我的数据集:我有一个连接销售、产品和客户的查询。好像是这样的:

customer_type | region | product_name | date       | sale_value
smallstore    | north  | chair        | 2016-01-01 | 22482
mediumstore   | south  | table        | 2016-02-02 | 50582
bigstore      | east   | desktop      | 2016-02-02 | 83737
smallstore    | north  | chair        | 2015-01-01 | 23828
mediumstore   | south  | coach        | 2015-02-02 | 93833
bigstore      | east   | desktop      | 2015-02-02 | 83282

查询将如下所示:

select 
c.customer_type,
c.region,
p.product_name,
s.date,
sum(s.sale_value)
from
sales s 
inner join products p on p.id = s.product_id
inner join customers c on c.id = s.customer_id
group by c.customer_type, c.region, p.product_name, s.date,

我需要得到下一个结果:

customer_type | region | product_name | date       | sales2015 | sales2016
smallstore    | north  | chair        | 2015-01-01 | 23828     | 22482
mediumstore   | south  | table        | 2016-02-02 | 0         | 50582
mediumstore   | south  | coach        | 2015-02-02 | 93833     | 0
bigstore      | east   | desktop      | 2015-02-02 | 83282     | 83737

换句话说:我需要为每个 customer_type、区域和 product_name 获取其 2015 年与 2016 年相比的销售额。

如何更改查询以获取该查询?我尝试了

形式的子查询的不同变体
select
c.customer_type,
c.region,
p.product_name,
s.date,
( select sum(sale_value) from ... where date between 2015-01-01 and 2015-12-31 group by ...) as sales2015,
( select sum(sale_value) from ... where date between 2016-01-01 and 2016-12-31 group by ...) as sales2016,
from
sales s 
inner join products p on p.id = s.product_id
inner join customers c on c.id = s.customer_id
group by c.customer_type, c.region, p.product_name, s.date,

但是我在选择之间得到了交叉产品,因为没有 id 可以将子查询与主查询连接起来。我也不知道如何管理一年或另一年的缺失值。

非常感谢您的帮助。

代替子查询,您可以使用:

...
sum(iif(year(date)=2015,sale_value,0)) as sales2015,
sum(iif(year(date)=2016,sale_value,0)) as sales2016,
...

此外,您应该从 select 和分组依据中删除 s.date。