如何对列中的顺序数据求和?

时间:2017-03-21 11:18:29

标签: sql sql-server sql-server-2008

我遇到了一个查询,当列(distance)为1时,我必须对列(ignition)求和,该列为1时。

enter image description here

例如答案:208和12.到目前为止我所尝试的是我发现序列已经中断但无法继续前进

WITH CTE AS 
(
    SELECT TOP 2147483647
        rownum = ROW_NUMBER() OVER (ORDER BY p.DeviceTimestamp),
        p.TrackedPointID,
        p.Ignition
    FROM 
        trackedpoints p 
    ORDER BY 
        p.DeviceTimestamp
)
SELECT
    cte.TrackedPointID,
    prev.Ignition PreviousValue,
    CTE.Ignition,
    nex.Ignition NextValue
FROM 
    CTE
LEFT JOIN 
    CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN 
    CTE nex ON nex.rownum = CTE.rownum + 1
WHERE
    prev.Ignition = 0 
    AND cte.Ignition = 1
GO

1 个答案:

答案 0 :(得分:2)

您需要识别相邻值的组。一种方法是行数的差异:

select min(DeviceTimestamp), max(DeviceTimestamp), sum(distance)
from (select tp.*,
             row_number() over (order by DeviceTimestamp) as seqnum,
             row_number() over (partition by ignition order by DeviceTimestamp) as seqnum_i,
      from trackedpoints tp
     ) tp
where ignition = 1
group by (seqnum - seqnum_i);

解释为什么行数的差异识别相同的相邻值有点棘手。但是,如果运行子查询并查看结果,则可以看到差异如何定义这些组。

另请注意,where子句需要进入外部查询。否则,分隔相邻“1”组的“0”值将不可见。