Home Forums SQL Server 2008 T-SQL (SS2K8) read the current row and previous row & calculate difference reporting values over RE: read the current row and previous row & calculate difference reporting values over

  • This has been solved in other posts and seems to be a very common issue.

    Here's one solution (I added DDL and sample data in an usable format and you should try to do this for your next posts, as it will give you better and faster answers).

    DECLARE @Tabletable(

    idint,

    device int,

    value int)

    INSERT @Table

    SELECT 9, 456, 70 UNION ALL

    SELECT 8, 456, 60 UNION ALL

    SELECT 7, 123, 70 UNION ALL

    SELECT 6, 123, 60 UNION ALL

    SELECT 5, 456, 50 UNION ALL

    SELECT 4, 456, 10 UNION ALL

    SELECT 3, 123, 50 UNION ALL

    SELECT 2, 123, 20 UNION ALL

    SELECT 1, 123, 10 ;

    WITH CTE AS (

    SELECT id,

    device,

    value,

    ROW_NUMBER() OVER(ORDER BY device, id) rownum

    FROM @Table)

    SELECT a.id

    FROM CTE a

    JOIN CTE b ON a.rownum = b.rownum + 1

    WHERE a.value - b.value > 20

    EDIT: See what I meant when saying this is only one solution? Now you have three different ones but one could have problems with missing ids. And mine had probably a problem with the order (corrected now).

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2