简体   繁体   English

如何在子查询中使用ORDER BY

[英]How to use ORDER BY in subqueries

update dbo.Sheet1$ set F01 = 0 where ID in(
select top 3 ID from dbo.Sheet1$ where ID in(
select ID, ISNULL(F01,0) + ISNULL(F02,0) + ISNULL(F03,0) as RowSum 
   from dbo.Sheet1$ where F01 = 1 AND F02 = 1 order by RowSum desc))

Running this code I get the error message: 运行此代码,我收到错误消息:

Msg 1033, Level 15, State 1, Line 1 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified. 消息1033,级别15,状态1,行1除非也指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

can I write another query that exactly does the same like above query? 我可以编写另一个与上述查询完全相同的查询吗?

Your query has more issues than just ordering without sampling. 您的查询所涉及的问题不只是订购而不进行抽样。 For example, when you use a subquery inside the IN () predicate, it cannot return more than 1 column, while your returns two. 例如,当您在IN ()谓词中使用子查询时,它不能返回多于1列,而您将返回两列。

Check this one, maybe I have guessed it correctly: 检查一下,也许我猜对了:

update dbo.Sheet1$ set F01 = 0
where ID in (
    select top 3 ID
    from dbo.Sheet1$
    where F01 = 1 AND F02 = 1
    order by ISNULL(F01,0) + ISNULL(F02,0) + ISNULL(F03,0) desc
);

2 possible reasons for the errors are: 错误的2个可能原因是:

1) You subquery has condition IN which tries to look for 2 column in the subquery while you can have only 1 column while you query IN 1)您的子查询具有条件IN,该条件试图在子查询中查找2列,而在查询IN时只能有1列

2) Your subquery can not use Order By because whether you're going to sort or not, it'll look for matching records from the subquery result set and update the records. 2)您的子查询不能使用Order By,因为无论您是否要排序,它都会从子查询结果集中查找匹配的记录并更新记录。 So there won't be any meaning of using Order By in your subquery. 因此,在子查询中使用Order By不会有任何意义。 Whether you'll keep Order By or remove Order By in your subquery, it'll give you the same output. 无论是在子查询中保留Order By还是删除Order By,它都会为您提供相同的输出。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM