【问题标题】:The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries - Where the top should be?ORDER BY 子句在视图、内联函数、派生表、子查询中无效 - 顶部应该在哪里?
【发布时间】:2014-08-09 18:19:04
【问题描述】:

我收到此错误:

ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP 或 FOR XML

从这个查询:

(SELECT Z.dMonth,Z.dCount FROM (
 SELECT COUNT(*) dCount, month(tblDiving.date_of_diving) as dMonth
 FROM tblDiving
 GROUP BY month(tblDiving.date_of_diving) 
)Z
ORDER BY Z.dCount)

我知道我需要在此查询中的某处添加“Top”,但在何处? 最后,这个查询需要返回Maximum dCount和这个dCount的月份。

已编辑:

This is my query:
select tblSite.name,tblSite.site_length,tblSite.site_depth,tblSite.water_type,tblSite.country,
COUNT(distinct tblDivingClub.number) as number_of_clubs,
COUNT(distinct tblDiving.diving_number) as number_of_divings,
COUNT(distinct tblDiving.guide) as number_of_guids,
sum(tblDiving.number_of_divers) as number_of_divers,
(SELECT top 1 Z.dMonth,Z.dCount FROM (
 SELECT COUNT(*) dCount, month(tblDiving.date_of_diving) as dMonth
FROM tblDiving 
GROUP BY month(tblDiving.date_of_diving) 
 )Z
ORDER BY Z.dCount)
from tblCountry inner join
tblSite on tblCountry.name=tblSite.country
inner join tblDiving on tblSite.name = tblDiving.diving_site
inner join tblDivingClub on tblDiving.diving_club = tblDivingClub.number
where tblSite.name in(select tblSite.name from tblSite where tblSite.country = 'Greece' ) and 
tblDiving.date_of_diving >= DATEADD(year,-1, GETDATE())
group by tblSite.name,tblSite.site_length,tblSite.site_depth,tblSite.water_type,tblSite.country

现在的错误是:当没有用EXISTS引入子查询时,选择列表中只能指定一个表达式

【问题讨论】:

  • (SELECT TOP 1 Z.dMonth...

标签: sql-server


【解决方案1】:

我认为这应该可行

SELECT Z.dMonth
  ,Z.dCount
FROM (
SELECT COUNT(*) dCount
    ,month(tblDiving.date_of_diving) AS dMonth
FROM tblDiving
GROUP BY month(tblDiving.date_of_diving)
HAVING COUNT(*) = (
        SELECT MAX(A.Count)
        FROM (
            SELECT COUNT(*) Count
                ,tblDiving.date_of_diving
            FROM tblDiving
            GROUP BY tblDiving.date_of_diving
            ) A
        )
) Z

【讨论】:

  • @user3926004 我不明白为什么,但它仍然给我同样的错误:(
【解决方案2】:

为什么不直接做:

SELECT TOP(1) COUNT(*) AS dCount, MONTH(tblDiving.date_of_diving) AS dMonth
FROM tblDiving
GROUP BY MONTH(tblDiving.date_of_diving)
ORDER BY dCount

【讨论】:

  • 因为它是一个子查询。我需要从这个查询中只选择最大 dCount,而不是所有 dCount。
  • 是的。但是虽然我选择了top 1,但我得到了这个错误:当没有用EXISTS引入子查询时,选择列表中只能指定一个表达式
【解决方案3】:

微软在这里解释它 - http://support.microsoft.com/kb/841845

来自文档 -

"当您在视图、内联函数、派生表或子查询中使用 ORDER BY 子句时,它不保证有序输出。相反,ORDER BY 子句仅用于保证结果集由 Top 运算符生成具有一致的构成。ORDER BY 子句仅在最外层的 SELECT 语句中指定时才保证有序的结果集。”

在你的情况下,如果你想退回所有东西,你可以选择前 100%,或者如果你需要的话,只选择前 1 个。

(SELECT TOP 1 Z.dMonth,Z.dCount FROM (
 SELECT COUNT(*) dCount, month(tblDiving.date_of_diving) as dMonth
 FROM tblDiving
 GROUP BY month(tblDiving.date_of_diving) 
)Z
ORDER BY Z.dCount)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多