我正在使用 MS SQL 2005,并创建了一个 CTE 查询来返回最后两条记录的值。然后我用它来查找返回的两个数字的增量。我有各种各样的工作查询,但我在获取除 delta 数字之外的任何内容时遇到问题。
这是我的查询:
;with data as(
SELECT
NetObjectID,
RawStatus,
RowID,
rn
from(
SELECT
CustomPollerAssignmentID AS NetObjectID,
RawStatus,
RowID,
row_number() over(order by DateTime desc)as rn
FROM CustomPollerStatistics_Detail
WHERE
(CustomPollerAssignmentID='a87f531d-4842-4bb3-9d68-7fd118004356')
) x where rn<=2
)
SELECT
case when
max(case rn when 1 then RawStatus end) > max(case rn when 2 then RawStatus end)
then
max(case rn when 1 then RawStatus end) - max(case rn when 2 then RawStatus end)
else
max(case rn when 2 then RawStatus end) - max(case rn when 1 then RawStatus end)
end as Delta
from data having
(SELECT
case when
max(case rn when 1 then RawStatus end) > max(case rn when 2 then RawStatus end)
then
max(case rn when 1 then RawStatus end) - max(case rn when 2 then RawStatus end)
else
max(case rn when 2 then RawStatus end) - max(case rn when 1 then RawStatus end)
end
from data) >= 1
我所追求的是返回 Delta 和 NetObjectID。每次我尝试,我都会得到错误。
data.NetObjectID is invalid in the select list because it is not contained in either an aggregate function or the group by clause.
如果我尝试将 group by 等添加到查询的末尾,我会收到更多错误,抱怨“组”这个词。
我对 SQL 比较陌生,我边走边学。任何帮助将不胜感激。