按查询挑战分组

时间:2009-01-09 18:25:33

标签: sql mysql

我有这些表格:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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的使用需要括号,并且只接受将与=进行比较的列列表。您无法使用USING语法使用ON语法提供完整的比较表达式。

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

另请参阅“Query: count multiple aggregates per item