使用CASE WHEN获取特定年份的订单

时间:2017-06-04 14:20:43

标签: sql left-join case-when

我正在使用此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加载了数据。

1 个答案:

答案 0 :(得分:2)

  1. CASE进入SUM()
  2. 使用单引号进行字符串比较。
  3. 结果查询:

    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;