select一次查询的结果在另一个表中发生

时间:2011-07-31 21:20:26

标签: sql

假设我有两张桌子:

USERS:
User_Id
Hansen
Nilsen
Jensen
Bob

ORDERS:
O_Id    OrderDate   OrderPrice  Customer
1       2008/11/12  1000        Hansen
2       2008/10/23  1600        Nilsen
3       2008/09/02  700         Hansen
4       2008/09/03  300         Hansen
5       2008/08/30  2000        Jensen
6       2008/10/04  100         Nilsen

我想查询一下客户订购的次数,看起来像是:

Customer    Orders
Hansen      3
Nilsen      2
Jensen      1
Bob         0

我知道我必须使用COUNT函数,但我对如何完成此查询感到茫然......

1 个答案:

答案 0 :(得分:5)

SELECT     Customer, COUNT(*) AS Orders 
FROM         ORDERS  RIGHT OUTER JOIN
                      USERS ON USERS.User_Id = ORDERS.Customer
GROUP BY USERS.User_Id
ORDER BY COUNT(*) DESC