Denne tilgang er til MySQL. Den bruger en kombination af variabler i en ordnet underforespørgsel til at etablere en fælles startdato for hvert "område". CROSS JOIN bruges kun til at initialisere variablerne, det ændrer ikke antallet af rækker. Når den fælles startdato er etableret, bliver den en simpel gruppe for forespørgsel i den ydre forespørgsel.
SELECT Item, LOC, RP_IND, dr_begin, MAX(RP_DATE) dr_end
FROM (
SELECT
mytable.*
, @fin := CONVERT(IF(@item<=>item AND @loc<=>loc AND DATEDIFF(rp_date, @d)=1, @fin, rp_date), DATE) AS dr_begin
, @item := item
, @loc := loc
, @d := rp_date
FROM mytable CROSS JOIN (SELECT @item:=NULL, @loc:=NULL, @d:=NULL, @fin := NULL) AS init
ORDER BY item, loc, rp_date
) d
GROUP BY Item, LOC, RP_IND, dr_begin
;
+----+------------+-----+--------+------------+---------------------+
| | Item | LOC | RP_IND | dr_begin | dr_end |
+----+------------+-----+--------+------------+---------------------+
| 1 | 1003785256 | 543 | Y | 2016-11-05 | 07.11.2016 00:00:00 |
| 2 | 1003785256 | 543 | Y | 2016-11-09 | 10.11.2016 00:00:00 |
| 3 | 1003790365 | 150 | Y | 2016-11-05 | 05.11.2016 00:00:00 |
| 4 | 1003797790 | 224 | Y | 2016-11-05 | 08.11.2016 00:00:00 |
+----+------------+-----+--------+------------+---------------------+
Bemærk <=> returnerer 1, hvis begge operander er NULL a>
Se forespørgslen på:http://rextester.com/SEYG96251
#drop table mytable;
CREATE TABLE mytable(
Item INTEGER NOT NULL
,LOC INTEGER NOT NULL
,RP_DATE DATE NOT NULL
,RP_IND VARCHAR(1) NOT NULL
);
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003785256,543,'2016-11-05','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003785256,543,'2016-11-06','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003785256,543,'2016-11-07','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003785256,543,'2016-11-09','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003785256,543,'2016-11-10','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003790365,150,'2016-11-05','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003797790,224,'2016-11-05','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003797790,224,'2016-11-06','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003797790,224,'2016-11-07','Y');
INSERT INTO mytable(Item,LOC,RP_DATE,RP_IND) VALUES (1003797790,224,'2016-11-08','Y');