SQL查询选择放置了最多订单的客户端

时间:2013-02-13 10:15:10

标签: sql

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

我有两张桌子:

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; 

我该怎么做?

6 个答案:

答案 0 :(得分:2)

因为 不一定 对于你正在使用的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; 

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

答案 2 :(得分:1)

您的create table包含错误的语法

试试这个

   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;

答案 3 :(得分:1)

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

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

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