2009-01-09 89 views
1

我有这些表:组通过查询挑战

customer 
-------- 
customer_id int 
name  varchar(255) 

order 
----- 
order_id int 
customer_id int 
discount boolean 

我可以像查询得到每个客户做出订单数:

select c.id, count(o.order_id) 
from customer c 
left join order as o using c.customer_id = o.customer_id 
group by 1 

或者,我可以得到的数每个客户打折订单:

select c.id, count(o.order_id) 
from customer c 
left join order as o using c.customer_id = o.customer_id and o.discount = true 
group by 1 

但我找不出一个方法来在一个单一的查询。我试过以下内容:

select c.id, count(o.order_id), count(o2.order_id) 
from customer c 
left join order as o using c.customer_id = o.customer_id 
left join order as o2 using c.customer_id = o2.customer_id and o2.discount = true 
group by 1 

但它没有奏效。是否可以在单个(MySql)查询中计算两者?

干杯, 唐

回答

3

如何像

select c.id, count(o.order_id),sum(if(o.discount,1,0)) 
from customer c 
left join order as o using c.customer_id = o.customer_id 
group by c.id 
+0

在不具有IF函数,CASE表达式或DECODE系统函数可以用来代替。 – 2009-01-09 18:32:17

1

你可以做出头像

select 
c.id, 
sum(case o.discount when true then 1 else 0 end) as 'total discounted', 
count(o.order_id) as 'total orders' 
from customer as c 
left join order as o using c.customer_id = o.customer_id 
group by c.id 
1

其他答案接近,但在这里就是我会写:

SELECT c.id, COUNT(o.order_id) AS order_count, 
    SUM(o.discount = true) AS discount_order_count 
FROM customer c 
    LEFT OUTER JOIN order AS o USING (customer_id) 
GROUP BY c.id; 

请注意,使用USING需要括号,并且它只接受将与=进行比较的列的列表。您无法像使用ON语法一样使用USING语法提供完整的比较表达式。

此外可以简化内SUM()表达因为相等比较返回1或0。

还请参见“Query: count multiple aggregates per item