SQL Query to find the earliest date depending on a change in a column value

I have a problem when I need to get the earliest date value from a table, grouped by column but sequentially grouped.

Here is an example table:

if object_id('tempdb..#tmp') is NOT null 
    DROP TABLE #tmp

CREATE TABLE #tmp
(
    UserID              BIGINT      NOT NULL,
    JobCodeID           BIGINT      NOT NULL,
    LastEffectiveDate   DATETIME    NOT NULL
)

INSERT INTO #tmp VALUES ( 1, 5, '1/1/2010') 
INSERT INTO #tmp VALUES ( 1, 5, '1/2/2010') 
INSERT INTO #tmp VALUES ( 1, 6, '1/3/2010') 
INSERT INTO #tmp VALUES ( 1, 5, '1/4/2010') 
INSERT INTO #tmp VALUES ( 1, 1, '1/5/2010') 
INSERT INTO #tmp VALUES ( 1, 1, '1/6/2010')

SELECT JobCodeID, MIN(LastEffectiveDate)
FROM #tmp
WHERE UserID = 1
GROUP BY JobCodeID

DROP TABLE [#tmp]

This query will return 3 rows with a minimum value.

1   2010-01-05 00:00:00.000
5   2010-01-01 00:00:00.000
6   2010-01-03 00:00:00.000

I am looking for a group to be consistent and return more than one JobCodeID, for example:

5   2010-01-01 00:00:00.000
6   2010-01-03 00:00:00.000
5   2010-01-04 00:00:00.000
1   2010-01-05 00:00:00.000

Is this possible without a cursor?

+3
source share
2 answers
SELECT  JobCodeId, MIN(LastEffectiveDate) AS mindate
FROM    (
        SELECT  *,
                prn - rn AS diff
        FROM    (
                SELECT  *,
                        ROW_NUMBER() OVER (PARTITION BY JobCodeID 
                                    ORDER BY LastEffectiveDate) AS prn,
                        ROW_NUMBER() OVER (ORDER BY LastEffectiveDate) AS rn
                FROM    @tmp
                ) q
        ) q2
GROUP BY
        JobCodeId, diff
ORDER BY
        mindate

Continuous ranges have the same difference between partitioned and unallocated ROW_NUMBERs.

You can use this value in GROUP BY.

. , :

+4

- , temp, . , . , ( LastEffectiveDate):

DECLARE @tmp table
(
    Sequence            INT IDENTITY,
    UserID              BIGINT,
    JobCodeID           BIGINT,
    LastEffectiveDate   DATETIME
)

INSERT INTO @tmp VALUES ( 1, 5, '1/1/2010') 
INSERT INTO @tmp VALUES ( 1, 5, '1/2/2010') 
INSERT INTO @tmp VALUES ( 1, 6, '1/3/2010') 
INSERT INTO @tmp VALUES ( 1, 5, '1/4/2010') 
INSERT INTO @tmp VALUES ( 1, 1, '1/5/2010') 
INSERT INTO @tmp VALUES ( 1, 1, '1/6/2010')

SELECT TOP 1 JobCodeID, LastEffectiveDate
FROM @tmp

UNION ALL

SELECT t2.JobCodeID, t2.LastEffectiveDate
FROM @tmp t1
    INNER JOIN
        @tmp t2
        ON t1.Sequence + 1 = t2.Sequence
WHERE t1.JobCodeID <> t2.JobCodeID

, , , , , .

+1

Source: https://habr.com/ru/post/1727875/


All Articles