我需要帮助从sql中获得某些结果 用户表:
userid | name
-------|-----------
1 | Bob Robert
2 | Steve Smith
3 | Willard Henegar
4 | Max Rockwell
5 | Marion Paley
6 | Marcus Delisle
订单表:
orderid | userid
--------|-------
1 |1
2 |1
3 |1
4 |2
5 |3
6 |2
7 |4
8 |4
9 |5
10 |4
11 |4
12 |1
想要的结果
numOrders | numPeople
----------|----------
0 |1
1 |2
2 |1
3 |0
4 |2
所以基本上我想表明有多少人没有订单,有多少人有1个订单,2个订单等
我试图搞清楚并想出了这个:
SELECT
Count(orders.orderid) AS numOrders,
Count(users.userid) AS numPeople
FROM users
LEFT JOIN orders
ON users.userid = orders.userid
GROUP BY numOrders
但这给了我一个错误,我无法对numOrders进行分组。
关于如何实现这一目标的任何建议?
答案 0 :(得分:2)
你想要一个双直方图。这是最简单的方法:
select cnt, count(*), min(userid), max(userid)
from (select u.userid, count(o.userid) as cnt
from users u left join
orders o
on u.userid = o.userid
group by u.userid
) u
group by cnt;
但是,这不会为您提供0计数的行。这需要更多的努力。如果您有一个numbers
表来填补缺失的值,这会有所帮助。
答案 1 :(得分:1)
select count(userid), numorders
from(
SELECT
Count(*) AS numOrders,
userid
from orders
group by userid ) t
group by numorders
Orders
表就足够了,因为您只需要订单和用户数。
答案 2 :(得分:1)
如果您还希望用户没有任何订单,您可以执行以下操作:
select NumOrders, count(*) as NumPeople
from (
select u.UserId, count(*) as NumOrders
from users u
left join orders o on o.UserId = o.UserId
group by o.UserId
) t
group by t.NumOrders
你也可以这样做:
select NumOrders, count(*) as NumPeople
from (
select
u.UserId,
(select count(*) from orders o where o.UserId = u.UserId) as NumOrders
from users u
) t
group by t.NumOrders
戈登提到,拥有一张数字表会有所帮助。如果你知道没有人会说超过1000个订单,并且你想要为每个0到1000的数字显示一行,你可以这样做:
select number as NumPeople, isnull(p.NumOrders, 0) as NumOrders
from master..spt_values v
left join
(
select t.NumOrders, count(*) as NumPeople
from ( select
u.UserId,
(select count(*) from order o where o.UserId = u.UserId) as NumOrders
from users u) t
group by NumOrders
) p on p.NumOrders = v.number
where type = 'P'
and number <= 1000
以上内容适用于SQL Server。我不确定MySQL是否有主值表,否则,您可以轻松创建一个数字表并将其交换出来。