SQL Server - 查找具有最大订单的前n位客户

时间:2013-10-29 01:17:55

标签: sql sql-server join subquery inner-join

我想找到最多订单的前2名客户 该表看起来像:

CustomerId  OrderId ProductId
101         1       A
101         3       B
101         4       C
102         9       D
102         9       E
103         11      E
103         22      F

这是SELECT查询所需的输出:

CustomerId  OrderId 
101         1
101         3
101         4
103         11
103         22  

解决方案只是没有点击我的想法...我使用以下查询到达了一半 -

SELECT CustomerId, OrderId
FROM dbo.CustomerOrder
GROUP BY CustomerId, OrderId

它只给了我不同的CustomerId,OrderId。

任何人都可以帮忙。

7 个答案:

答案 0 :(得分:3)

以下是显示以下代码的SQL Fiddle示例:

SELECT DISTINCT CO.CustomerId, CO.OrderID FROM 
(
  SELECT TOP(2) COS.CustomerId, COUNT(DISTINCT COS.orderId) as NoOfOrders
  FROM custorders AS COS
  GROUP BY COS.CustomerId
  ORDER BY COUNT(DISTINCT COS.orderId) DESC, CustomerId  DESC
) AS COM 
INNER JOIN custorders AS CO
  ON COM.CustomerId = CO.CustomerId

答案 1 :(得分:1)

试试这个:

SELECT c.CustomerId, c.OrderId
FROM CustomerOrder c
INNER JOIN
(SELECT TOP 2 WITH TIES CustomerId, COUNT(distinct OrderId) as Count
FROM CustomerOrder
GROUP BY CustomerId
ORDER BY Count DESC) b ON c.CustomerId = b.CustomerId

您可以使用WITH TIES,例如,如果您有3个客户具有相同的最大订单数量,WITH TIES将检索这三个订单,如果没有这个,您将在外面放一个,这可能是错误的。

选中此SQL FIDDLE DEMO

答案 2 :(得分:1)

我会使用子选择来查找订单最多的客户。这是一个有效的例子:

DECLARE @orders AS TABLE(CustomerId INT, OrderId INT, ProductId VARCHAR(10))
INSERT INTO @orders VALUES(101, 1, 'A')
INSERT INTO @orders VALUES(101, 3, 'B')
INSERT INTO @orders VALUES(101, 4, 'C')
INSERT INTO @orders VALUES(102, 9, 'D')
INSERT INTO @orders VALUES(102, 9, 'E')
INSERT INTO @orders VALUES(103, 11, 'E')
INSERT INTO @orders VALUES(103, 22, 'F')

SELECT DISTINCT
    O.CustomerId,
    O.OrderId
FROM @orders O
JOIN (
    SELECT TOP 2 CustomerId, COUNT(DISTINCT(OrderId)) as OrderCount
    FROM @orders
    GROUP BY CustomerId
    ORDER BY COUNT(DISTINCT(OrderId)) DESC, CustomerId
) O2 ON O2.CustomerId = O.CustomerId
ORDER BY O.CustomerId, O.OrderId

在子选择中,我添加了一个次要排序来打破订单计数的关系。

答案 3 :(得分:0)

with CustomerOrders as
(
select CustomerId, count(orderId) as NoOfOrders
from dbo.CustomerOrder
group by CustomerId
)
select top 2 * from CustomerOrders
order by NoOfOrders desc

答案 4 :(得分:0)

select customername from customers where customerid  in 
   (select top 2 customerid from 
       (select count(*), customerid FROM orders
        group by customerid
        order by count(*) DESC))

答案 5 :(得分:0)

SELECT customer.cust_name, order.order_amount
FROM customer inner join order
ON customer.cust_id = order.cust_id
ORDER BY order.order_amount DESC

答案 6 :(得分:0)

select customerid,orderid from customerOrders 
group by CustomerId,OrderId 
having count(orderid) =1