Вы можете рассматривать это как разрывы и проблемы . Использование:
SELECT Article, EANUPC, MRP, DataDate,
ROW_NUMBER() OVER (PARTITION BY Article ORDER BY DataDate) -
ROW_NUMBER() OVER (PARTITION BY Article, MRP ORDER BY DataDate) AS grp
FROM mytable
ORDER BY DataDate
вы получите:
Article EANUPC MRP DataDate grp
---------------------------------------
20171554001 1220636 599 2015-11-20 0
20171554001 1220636 599 2017-12-15 0
20171554001 1220636 390 2017-12-26 2
20171554001 1220636 390 2018-01-11 2
20171554001 1220636 290 2018-01-16 4
20171554001 1220636 290 2018-01-24 4
20171554001 1220636 190 2018-01-30 6
20171554001 1220636 90 2018-02-06 7
20171554001 1220636 90 2018-06-13 7
20171554001 1220636 599 2018-06-13 7
Теперь вы можете заключить указанный выше запрос в CTE
и выполнить группировку, используя поле grp
:
;WITH CTE AS (
SELECT Article, EANUPC, MRP, DataDate,
ROW_NUMBER() OVER (PARTITION BY Article ORDER BY DataDate) -
ROW_NUMBER() OVER (PARTITION BY Article, MRP ORDER BY DataDate) AS grp
FROM mytable
)
SELECT Article, EANUPC, MRP, MIN(DataDate) AS FromDate
FROM CTE
GROUP BY Article, EANUPC, MRP, grp
Выход:
Article EANUPC MRP FromDate
----------------------------------
20171554001 1220636 599 2015-11-20
20171554001 1220636 390 2017-12-26
20171554001 1220636 290 2018-01-16
20171554001 1220636 190 2018-01-30
20171554001 1220636 90 2018-02-06
20171554001 1220636 599 2018-06-13
Вы можете получить окончательный результат, используя LEAD
:
;WITH CTE AS (
SELECT Article, EANUPC, MRP, DataDate,
ROW_NUMBER() OVER (PARTITION BY Article ORDER BY DataDate) -
ROW_NUMBER() OVER (PARTITION BY Article, MRP ORDER BY DataDate) AS grp
FROM mytable
), CTE2 AS (
SELECT Article, EANUPC, MRP, MIN(DataDate) AS FromDate
FROM CTE
GROUP BY Article, EANUPC, MRP,grp
)
SELECT Article, EANUPC, MRP, FromDate,
COALESCE(DATEADD(day, -1, LEAD(FromDate) OVER (ORDER BY FromDate)), FromDate) AS ToDate
FROM CTE2
Выход:
Article EANUPC MRP FromDate ToDate
----------------------------------------------
20171554001 1220636 599 2015-11-20 2017-12-25
20171554001 1220636 390 2017-12-26 2018-01-15
20171554001 1220636 290 2018-01-16 2018-01-29
20171554001 1220636 190 2018-01-30 2018-02-05
20171554001 1220636 90 2018-02-06 2018-06-12
20171554001 1220636 599 2018-06-13 2018-06-13