2

我想选择下订单最多的客户:

我有 2 张桌子:

CREATE TABLE customers(
customerid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME CHAR(50) NOT NULL,
address CHAR(100) NOT NULL,
city CHAR(30)NOT NULL
);


CREATE TABLE orders(
orderid INT UNSIGNED NOT NULL,
customerid INT UNSIGNED NOT NULL,
);

这就是我想要做的:

SELECT customers.customerid, customers.name,orders.orderid, COUNT(customerid) 
AS CostumerCount 
FROM customers 
INNER JOIN orders 
ON customers.customerid=orders.orderid; 

我怎么能做这个?

4

6 回答 6

3

由于您使用的 RDBMS不一定适合您,因此让我假设您使用的是 MySQL,并且您正在寻找具有最高订单数的客户:

SELECT 
  customers.customerid, 
  customers.name,
  COUNT(orders.orderid) AS Orderscount
FROM customers 
INNER JOIN orders ON customers.customerid = orders.customerid 
GROUP BY customers.customerid, 
         customers.name
ORDER BY Orderscount DESC
LIMIT 1; 
于 2013-02-13T10:18:45.360 回答
1

您的创建表包含错误的语法

尝试这个

   CREATE TABLE customers(
   customerid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
   NAME CHAR(50) NOT NULL,
   address CHAR(100) NOT NULL,
   city CHAR(30)NOT NULL
   );


  CREATE TABLE orders(
  orderid INT UNSIGNED NOT NULL,
  customerid INT UNSIGNED NOT NULL 
  );                               ^----remove comma ',' from here

并且您的查询效果很好,只需替换COUNT(customerid)COUNT(customers.customerid)

在这里试试

  SELECT customers.customerid, customers.name,orders.orderid, COUNT(customers.customerid) 
   AS CostumerCount 
   FROM customers 
   INNER JOIN orders 
  ON customers.customerid=orders.orderid;
于 2013-02-13T10:23:21.967 回答
1
SELECT customers.customerid, customers.name, 
       orders.orderid, COUNT( orders.customerid ) AS CostumerCount
FROM customers
INNER JOIN orders ON customers.customerid = orders.customerid
于 2013-02-13T10:28:17.800 回答
1

对于SQL SERVER;

SELECT TOP (1) * FROM (
    SELECT customers.customerid, customers.name, COUNT(*) AS CostumerCount 
    FROM customers INNER JOIN orders 
               ON customers.customerid=orders.customerid
    GROUP BY customers.customerid, customers.name 
) A
ORDER BY CostumerCount DESC
于 2013-02-13T10:19:09.277 回答
0
SELECT * FROM Customers WHERE cno = (
    SELECT cno FROM (
        SELECT count(*) as ordCount, cno 
        FROM ORDERS
        GROUP BY cno HAVING ordCount >= (
            SELECT max(ordCount) 
            FROM ( 
                SELECT count(*) as ordCount, cno 
                FROM ORDERS 
                GROUP BY cno
                )
            )
        )
    )
于 2016-11-23T10:36:09.930 回答
0

我已经编辑了第一个答案,因为如果您有更多具有相同订单数量的客户,您只会得到第一个!

SELECT 
    customers.customerid, 
    customers.name,
    COUNT(orders.orderid) AS Orderscount
FROM customers 
INNER JOIN orders ON customers.customerid = orders.customerid 
GROUP BY customers.customerid, 
         customers.name
HAVING Orderscount =  (       
    SELECT COUNT(id) AS Orderscount
    FROM orders
    GROUP BY customerid
    ORDER BY Orderscount DESC
    LIMIT 1
)
于 2021-01-15T10:32:22.560 回答