我们可以在子查询中使用order by吗?如果不是为什么有时可以使用top(n)订单?

时间:2017-04-26 17:51:38

标签: sql subquery sql-order-by

我是尝试了解有关SQL的更多信息的入门级,

我有一个问题"我们可以在子查询中使用order by吗?"我确实找了一些文章说不,我们不能使用。

但另一方面,我在子查询中看到了使用top(n)和order by的例子:

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

所以现在我有点困惑。

有人可以提出建议吗?

非常感谢。

3 个答案:

答案 0 :(得分:0)

是的,我们可以在子查询中使用order by子句,例如我有一个名为product的表(检查表http://prntscr.com/f15j3z的屏幕截图)。如果有任何疑问,请将此查询提交给您,并将其还原。

select p1.* from product as p1 where product_id = (select p2.product_id from product as p2 order by product_id limit 0,1) 

答案 1 :(得分:0)

  1. 是的,你说得对,我们不能在内部查询中使用order by。因为它充当了一张桌子。当查询用于不同目的时,表本身需要进行排序。

  2. 在您的查询本身中,内部查询是使用Top 2选择一些记录。尽管这些只是前2条记录,但它们形成一个包含2条记录的表,足以将其识别为表并将其与另一张表

  3. 正确的查询将是: -

    SELECT * FROM
    (
        SELECT c.CustomerId, c.OrderId, DENSE_RANK() OVER(ORDER BY b.count DESC) AS RANK
    
        FROM CustomerOrder c
    
        INNER JOIN
    
        (SELECT CustomerId, COUNT(distinct OrderId) as Count
        FROM CustomerOrder   GROUP BY CustomerId) b 
    
        ON c.CustomerId = b.CustomerId
    ) a
    
    WHERE RANK IN (1,2);
    

    希望我已经回答了你的问题。

答案 2 :(得分:0)

是的,我们可以在子查询中使用order by,但使用它是没有意义的。 最好在外部查询中使用它。没有使用对子查询的结果进行排序,因为内部查询的结果将成为外部查询的输入,并且它不必对结果的顺序做任何事情。子查询。

相关问题