我已经开始刷新我的SQL知识,并尝试使用W3School schemas from this link练习一些挑战。我要解决的问题是“如何从订购了3种以上不同产品的Order and OrderDetails表中查找客户ID,并根据所下订单的数量将其分组为3 +,10 +订单的存储桶”
我的努力:
select Distinct(o.CustomerID),
case when count (Distinct (od.OrderID)) >=0 and count (Distinct (od.OrderID)) <= 1 then '0 - 1'
when count (Distinct (od.OrderID)) >= 2 and count (Distinct (od.OrderID)) <= 4 then '3-4'
else 'no match'
end As NumOrd
from Orders o join OrderDetails od where o.OrderID = od.OrderID group by od.OrderId having count (od.OrderID) > 1; syntax error or W3School which is not clearly saying what is wrong and is my approach correct?
更新:当我添加第二个case语句时,我得到语法错误或W3School,但并没有清楚地说出什么错误->基于@Gordon注释对此进行了更正。但是,即使有些客户订购了3次以上,现在所有记录都进入了第一桶。
select
o.CustomerID,
case
when count(distinct od.OrderID) between 3 and 9 then '3+'
when count(distinct od.OrderID) >= 10 then '10+'
end NumOrd
from Orders o inner join OrderDetails od
on o.OrderID = od.OrderID
group by o.CustomerID
having count(distinct od.OrderID) >= 3