假设我有一个客户表和一个销售订单表,其中包含以下模式:
具有以下定义:
我想实现以下查询:
For any customer whose sales_representer is 100, find the customer id,
customer name and the number of his overall orders.
我构建了以下查询:
select C.id, C.name, count(C.id)
from customer C, sales_order S
where C.id = S.customer_id and
S.sales_represntor = '100'
group by C.id, C.nname;
但是作为计数(C.id)的结果,我只获得sales_representer为100的销售数量。 我知道我可以添加另一个sales_order实例(即S2)并从中计算,但在我看来根本没有效果。
有人有解决方案吗?
谢谢
答案 0 :(得分:2)
您可以使用having
条款要求代表100至少进行一次销售:
select C.id
, C.name
, count(*) as TotalSaleCount
from customer C
join sales_order S
on C.id = S.customer_id
group by
C.id
, C.name
having count(case when S.sales_representor = '100' then 1 end) > 0
答案 1 :(得分:2)
您想通过条件聚合来解决这个问题:
select C.id, C.name, count(*) as Total_Orders,
sum(case when S.sales_representor = '100' then 1 else 0 end) as SR100_Orders
from customer C join
sales_order S
on C.id = S.customer_id
group by C.id, C.nname;
请注意,我还将查询更改为使用显式的,正确的join
语法。这就是你应该学习编写查询的方法。
答案 2 :(得分:2)
您可以使用相关子查询来计算销售数量。 (在SQLite中,子查询通常与连接一样有效。)
SELECT id,
name,
(SELECT COUNT(*)
FROM sales_order
WHERE customer_id = customer.id) AS orders
FROM customer
WHERE id IN (SELECT customer_id
FROM sales_order
WHERE sales_representer = '100')
如果您关注效率,则应使用EXPLAIN QUERY PLAN检查查询,甚至更好,只需测量它们。