代码之家  ›  专栏  ›  技术社区  ›  MarkKneen

帮助查找从最后两条记录返回的值的差异(增量)

  •  0
  • MarkKneen  · 技术社区  · 15 年前

    我使用的是ms sql 2005,我创建了一个cte查询来返回最后两条记录的值。然后我用这个来找到返回的两个数字的增量。我有一个工作问题,但是 除了三角洲的数字我什么都得不到。

    我的问题是:

    ;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还不太熟悉,而且我会边走边捡东西。如有任何帮助,我们将不胜感激。

    2 回复  |  直到 15 年前
        1
  •  0
  •   DForck42    15 年前

    看看这样的方法能不能奏效。

    ;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
    
        2
  •  0
  •   dsrekab    15 年前

    抱歉,我是新来的,我不确定CTE查询,但是在您定义数据之后,您正在选择大小写…作为…的增量意思是你的select语句中只有delta。再说一次,如果我离基地很远的话,很抱歉。