我有这些表格:
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)查询中计算两者?
干杯, 唐
答案 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。