我正在使用此order dataset并尝试获取2列数据,1998年订单之一以及1996年订单中的一个与每个卖家名称一起。
到目前为止我的SQL是:
select
salesperson.name,
case when strftime('%Y', order_date) = 1998 then sum(orders.number) end as sales_in_1998,
case when strftime('%Y', order_date) = 1996 then sum(orders.number) end as sales_in_1996
from salesperson
left join orders on orders.salesperson_id = salesperson.id
group by salesperson.name;
(抱歉没有YEAR()
函数,因为我将它加载到sqlite中)
但是,我只是为所有内容获取NULL。我做错了什么?
Here is my SQLfiddle加载了数据。
答案 0 :(得分:2)
CASE
进入SUM()
。结果查询:
select sp.name,
sum(case when strftime('%Y', o.order_date) = '1998' then o.number
end) as sales_in_1998,
sum(case when strftime('%Y', o.order_date) = '1996' then o.number
end) as sales_in_1996
from salesperson sp left join
orders o
on o.salesperson_id = sp.id
group by sp.name;