我正在將一些代碼從Oracle轉換爲SQL Server(2012),並遇到此子查詢使用PARTITION/ORDER BY檢索最近記錄的問題。子查詢單獨運行很好,但因爲它是一個子查詢,我發現了錯誤:查找子查詢中的最新記錄(SQL Server)
SQL Server Database Error: 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.
下面是SQL的部分:
FROM (
SELECT distinct enr.MemberNum,
(ISNULL(enr.MemberFirstName, '') + ' ' + ISNULL(enr.MemberLastName, '')) AS MEMBER_NAME,
enr.MemberBirthDate as DOB,
enr.MemberGender as Gender,
LAST_VALUE(enr.MemberCurrentAge) OVER (PARTITION BY MemberNum ORDER BY StaticDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS AGE,
LAST_VALUE(enr.EligStateAidCategory)OVER (PARTITION BY MemberNum ORDER BY StaticDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS EligStateAidCategory,
LAST_VALUE(enr.EligStateAidCategory)OVER (PARTITION BY MemberNum ORDER BY StaticDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS AID_CAT_ROLL_UP,
LAST_VALUE(enr.EligFinanceAidCategoryRollup)OVER (PARTITION BY MemberNum ORDER BY StaticDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS EligFinanceAidCategoryRollup,
SUM(enr.MemberMonth) OVER (PARTITION BY MemberNum) AS TOTAL_MEMBER_MONTHS
FROM dv_Enrollment enr
WHERE enr.StaticDate BETWEEN '01-JUN-2016' AND '30-JUN-2016'
)A
所以,我環顧四周,並發現你可以使用TOP(2147483647)破解,所以我試圖改變的第一行:
SELECT distinct TOP (2147483647) enr.MemberNum,
但我仍然得到同樣的錯誤。我想過的所有其他方式也需要ORDER BY(使用DENSE RANK等)。
我在子查詢中看不到'order by'。你能發佈完整的查詢文本嗎? –
你在'wHere'裏錯過了一個H – SqlZim
要小心'between' [壞習慣踢:錯誤處理日期/範圍查詢 - Aaron Bertrand - 2009-10-16](http://sqlblog.com/ blog/aaron_bertrand/archive/2009/10/16/bad-habits-to-kick-mishandling-date-range-queries.aspx) – SqlZim