问题- 显示由销售员Marshall处理的订单的客户ID,名称和订单总数,但前提是客户名称以General开头或以Electric结尾。排除下单的客户,但也包括不下订单的客户。根据订单总数的降序排序结果,然后按名称升序排序。 不要使用LIKE运算符,也不要联接3个表。
问题输出
当前查询
SELECT c.customer_id,
c.name,
Count(o.order_id) "# of Orders"
FROM customers c
left join orders o
ON c.customer_id = o.customer_id
WHERE Substr(c.name, 1, 7) = 'General'
OR Substr(c.name, -8) = 'Electric'
AND o.order_id IN (SELECT o.order_id
FROM orders o,
order_items oi
WHERE o.order_id = oi.order_id
AND o.salesman_id = (SELECT employee_id
FROM employees
WHERE
last_name = 'Marshall')
GROUP BY o.order_id
HAVING Count(customer_id) > 1)
GROUP BY c.customer_id,
c.name;
数据库-
不知道我在做什么错了。
答案 0 :(得分:0)
这是一个非常人为的任务...这是一个选择:
select c.customer_id, c.customer_name, count(o.orderid) cnt
from customers c
left join orders o
on o.customer_id = c.customer_id
and (select last_name from employee e where e.employee_id = o.salesman_id) = 'Marshall'
where substr(c.name, 1, 7) = 'General' or substr(c.name, -8) = 'Electric'
group by c.customer_id, c.customer_name
having count(o.orderid) <> 1
基本思想是left join
。 where
子句按客户名称过滤-不包含like
:您已经拥有了。
要过滤销售人员姓名而没有其他联接,我们在on
的{{1}}子句中使用相关子查询。无需携带left join
,也无需在order_items
中再次选择。
最后,对订单计数的过滤将转到orders
子句。