2

我想找到订单最多的前 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 对。

任何人都可以请帮忙。

4

7 回答 7

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
于 2013-10-29T01:33:04.557 回答
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 演示

于 2013-10-29T01:24:32.773 回答
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

在子选择中,我添加了二级排序以打破订单计数的关系。

于 2013-10-29T01:27:05.993 回答
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
于 2013-10-29T01:22:30.820 回答
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))
于 2014-04-06T11:54:26.260 回答
0
select customerid,orderid from customerOrders 
group by CustomerId,OrderId 
having count(orderid) =1
于 2017-04-15T23:08:33.960 回答
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
于 2016-05-27T07:09:40.290 回答