Я бы хотел, чтобы эта часть была выполнена автором вопроса.
DECLARE @Seller TABLE (
SellerID INT,
phonecalldate DATE,
[Sequence] INT,
Selling INT CHECK(Selling IN(0, 1)),
PRIMARY KEY (SellerID, phonecalldate, [Sequence])
);
INSERT @Seller(SellerID, phonecalldate, [Sequence], Selling)
VALUES
(100, '20180105', 1, 0),
(100, '20180105', 2, 0),
(100, '20180105', 3, 1),
(100, '20180105', 4, 0),
(100, '20180105', 5, 0),
(100, '20180110', 1, 0),
(100, '20180110', 2, 0),
(100, '20180110', 3, 0),
(100, '20180110', 4, 1),
(100, '20180110', 5, 0),
(100, '20180110', 6, 0),
(100, '20180110', 7, 0),
(100, '20180110', 8, 0),
(100, '20180110', 9, 0),
(100, '20180110', 10, 0);
Данные, необходимые для получения желаемого результата, можно получить с помощью следующего запроса:
WITH
a AS (
SELECT
SellerID,
Selling,
FORMAT(phonecalldate, 'yyyyMMdd') +
FORMAT([Sequence], '00000000') AS dump,
SUM(Selling) OVER
(
PARTITION BY SellerID
ORDER BY phonecalldate, [Sequence]
) AS g
FROM @Seller
)
SELECT
COUNT(*) AS PhoneCallQty,
CAST(LEFT(MIN(dump), 8) AS DATE) AS StartDate,
CAST(RIGHT(MIN(dump), 8) AS INT) AS StartSeq,
CAST(LEFT(MAX(dump), 8) AS DATE) AS EndDate,
CAST(RIGHT(MAX(dump), 8) AS INT) AS EndSeq
FROM a
WHERE Selling = 0
GROUP BY SellerID, g;
Выход:
+--------------+------------+----------+------------+--------+
| PhoneCallQty | StartDate | StartSeq | EndDate | EndSeq |
+--------------+------------+----------+------------+--------+
| 2 | 2018-01-05 | 1 | 2018-01-05 | 2 |
| 5 | 2018-01-05 | 4 | 2018-01-10 | 3 |
| 6 | 2018-01-10 | 5 | 2018-01-10 | 10 |
+--------------+------------+----------+------------+--------+