0

我正在使用 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 比较陌生,我边走边学。任何帮助将不胜感激。

4

2 回答 2

0

抱歉,我在这里很新,我不确定 CTE 查询,但是看起来在您定义数据之后,您正在选择 case ... as Delta FROM...。这意味着您的选择语句中只有 Delta。再次,对不起,如果我离基地很远。

于 2009-05-05T12:23:41.820 回答
0

看看这样的事情是否可行。

;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
    NetObjectID,
    max(RawStatus)-min(RawStatus) as Delta
from data
group by NetObjectID
于 2009-05-05T13:56:32.533 回答