在示例中使用子查询(查找具有条件的客户的所有订单)

时间:2014-11-21 01:24:33

标签: sql sql-server sql-server-2008 subquery

我遇到了一些查询问题。我需要做的是写出订单数量最多的客户的所有订单(从一张表中)。

所以我得到了这个(它有效并且告诉我哪个客户的订单数量最多):

SELECT custid, COUNT(*) as "Number of orders"
FROM sales.orders
GROUP BY custid
ORDER BY COUNT(*) DESC

然后我需要将此与另一个查询相结合,该查询从该客户订单中获得所有“ORDERID”。我尝试了不同的方法,但不是很好。最后我有这样的事情:

SELECT custid, orderid FROM sales.orders
WHERE EXISTS
(
    SELECT custid, COUNT(*) as "Number of orders"
    FROM sales.orders
    GROUP BY custid
)
ORDER BY COUNT(*) DESC

有错误:

  

“'SALES.ORDERS.custid'在选择列表中无效,因为它不是   包含在聚合函数或GROUP BY子句中。“

如何在这种情况下使用子查询使其工作?谢谢你的时间和答案!

3 个答案:

答案 0 :(得分:2)

SELECT custid,
       orderid
FROM   sales.orders
WHERE  custid = (SELECT TOP 1 custid
                 FROM   sales.orders
                 GROUP  BY custid
                 ORDER  BY Count(*) DESC) 

答案 1 :(得分:1)

SELECT custid, orderid FROM sales.orders
WHERE custid IN(
SELECT TOP 1 custid
FROM sales.orders
GROUP BY custid
ORDER BY COUNT(*) DESC)

这应该适用(对于MySQL),这里是一个SQL小提琴: http://sqlfiddle.com/#!2/d580a6/1

答案 2 :(得分:1)

;WITH CTE AS(
    SELECT TOP 1
        custId
    FROM sales.orders
    GROUP BY custId
    ORDER BY count(*) DESC
)
SELECT
    c.custId
    o.orderId
FROM CTE c
INNER JOIN sales.orders o
    on o.custId = c.custId