【问题标题】:Error when adding order by添加订单时出错
【发布时间】:2016-10-09 13:04:37
【问题描述】:

Goodday,请先检查我的查询。

SELECT *
FROM
( 
    SELECT DISTINCT row, a.tanggal, b.OutletCode, c.Nilai, a.Nip, b.Fullname,
        a.KodePenilaian, f.Description AS posisilama, d.ShortDesc AS posisibaru
    FROM penilaian_header a 
    LEFT JOIN Employee b
        ON a.Nip = b.Nip 
    LEFT JOIN Position f
        ON b.PositionCode = f.PositionCode 
    LEFT JOIN Position d
        ON a.PositionCode = d.PositionCode 
    LEFT JOIN arealeader g
        ON g.OutletCode = b.OutletCode 
    LEFT JOIN
    (
        SELECT ROW_NUMBER() OVER (PARTITION BY KodePenilaianH
                                  ORDER BY idPenilaiand DESC) AS Row,
            Nilai, KodePenilaianH
        FROM penilaian_Detail
    ) c
        ON a.KodePenilaian = c.KodePenilaianH 
    WHERE a.Outlet LIKE '%%' AND Periode LIKE '%%'
    ORDER BY b.OutletCode ASC
) nilai PIVOT (SUM(nilai) FOR ROW IN ([1],[2],[3],[4],[5])) piv;

我的问题是当我添加Order by 我的查询错误。这是错误:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

没有Order By,我的查询工作正常。

【问题讨论】:

  • 错误信息很清楚,您在子查询中使用了ORDER BY。也许您可以将TOP 添加到子查询中?

标签: sql sql-server-2008


【解决方案1】:

我认为是ORDER BY b.OutletCode ASC是错误的原因,而不是分区内的ORDER BY,这是必要的,应该允许的。

如果要返回所有记录,可以使用TOP,大数,例如

SELECT *
FROM
( 
    SELECT DISTINCT TOP 2147483647 row, a.tanggal, b.OutletCode, c.Nilai, a.Nip,
        b.Fullname, a.KodePenilaian, f.Description AS posisilama, d.ShortDesc AS posisibaru
    FROM penilaian_header a 
    LEFT JOIN Employee b
        ON a.Nip = b.Nip 
    ...
    ORDER BY b.OutletCode ASC
) nilai PIVOT (SUM(nilai) FOR ROW IN ([1],[2],[3],[4],[5])) piv;

【讨论】:

  • 这对我来说是一个很好的教训。谢谢。
  • 查看this SO answer 进行更深入的讨论。
猜你喜欢
  • 1970-01-01
  • 2020-06-15
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
相关资源
最近更新 更多