自从我使用SQL以来已经有一段时间了,所以我可能会陷入一些非常简单的事情,但事实如下:
Ill通过示例数据向我展示我的数据集:我有一个查询加入销售,产品和客户。看起来像这样:
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,region和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将子查询与主查询连接起来。我也不知道如何在一年或另一年内管理缺失值。
非常感谢您的帮助。
答案 0 :(得分:0)
您可以使用:
代替子查询=if(len(vlookup($A4,Match1!$B$6:$F,2,false))<1,vlookup($A4,Match1!$B$6:$F,5,false),if(vlookup($A4,Match1!$B$6:$F,2,false)="S","S",if(vlookup($A4,Match1!$B$6:$F,2,false)="F","F",0)))
此外,您应该从选择和组中删除s.date。