3

假设我有一个客户表和一个具有以下模式的销售订单表:

  1. 客户 = {id, name}
  2. Sales_order = {id, customer_id, sales_representer}

具有以下定义:

  1. id 是两个表中的主键。
  2. customer_id 是外键引用客户。

我想实现以下查询:

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;

但是由于 count(C.id) 我只得到了 sales_representer 为 100 的销售数量。我知道我可以添加另一个 sales_order 实例(即 S2)并从中计数,但在我看来根本没有效率.

有人有解决方案吗?

谢谢

4

3 回答 3

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
于 2013-07-27T12:29:44.000 回答
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语法。这就是您应该学习编写查询的方式。

于 2013-07-27T12:36:38.990 回答
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检查查询,或者更好的是,只需测量它们。

于 2013-07-27T16:17:43.780 回答