How to group by on consecutive values in SQL

后端 未结 2 1764
日久生厌
日久生厌 2021-01-28 13:59

I have a table in SQL Server 2014 with sample data as follows.

WK_NUM | NET_SPRD_LCL 
10       0 
11       1500 
12       3600 
13       3800 
14       4000

2条回答
  •  悲哀的现实
    2021-01-28 14:47

    First of all, when you say you want your query to 'output' and 'exit', it makes me think you are approaching t-sql as a procedural language, which it is not. Good t-sql queries are nearly always set based.

    In any case, before the query, let me add what is helpful for others to work with the data to build queries:

    DECLARE @t TABLE (WK_NUM INT, NET_SPRD_LCL INT);
    INSERT INTO @t VALUES 
    (10, 0),
    (11, 1500),
    (12, 3600),
    (13, 3800),
    (14, 4000);
    

    You say you are using SQL Server 2014, which means you have relevant window functions at your disposal. The one I am using (LAG) will have superior performance to using subqueries, which, if you insist on using, can be greatly improved by using TOP (1) with ORDER BY and an appropriate index instead of using a MIN function over the whole dataset. With tiny amounts of data you won't notice a difference, but on a real business system it will be obvious.

    Adjusted to provide the 2000 bonus on the correct line after OP's clarification:

    WITH cteTemp AS
        (
        SELECT  WK_NUM
            ,   thisValue = NET_SPRD_LCL
            ,   lastValue = LAG(NET_SPRD_LCL) OVER(ORDER BY WK_NUM)
        FROM @t
        WHERE WK_NUM < 27
        )
    , cteBonusWeek AS
        (
        SELECT  TOP (1)
                WK_NUM
            ,   bonus = 2000
        FROM cteTemp
        WHERE thisValue > 3500 AND lastValue > 3500
        ORDER BY WK_NUM
        )
    SELECT  t.WK_NUM
        ,   t.NET_SPRD_LCL
        ,   bonus = COALESCE(b.bonus, 0)
    FROM @t AS t
    LEFT JOIN cteBonusWeek AS b
        ON b.WK_NUM = t.WK_NUM;
    

提交回复
热议问题