DDL и пример данных:
CREATE TABLE atable (
SID int,
Sdate datetime,
Profit money,
Units int
);
INSERT INTO atable (SID, Sdate, Profit, Units)
SELECT 1, '7/26/2010 9:15:00 AM' , -37.5, -1 UNION ALL
SELECT 1, '7/26/2010 12:00:00 PM', -125 , -1 UNION ALL
SELECT 1, '7/26/2010 12:45:01 PM', -12.5, -1 UNION ALL
SELECT 1, '7/26/2010 12:45:02 PM', 0 , 0 UNION ALL
SELECT 1, '7/26/2010 12:45:03 PM', -75 , 1 UNION ALL
SELECT 1, '7/26/2010 2:00:01 PM' , -12.5, 1 UNION ALL
SELECT 1, '7/26/2010 2:00:02 PM' , 0 , 0 UNION ALL
SELECT 1, '7/26/2010 2:00:03 PM' , -125 , -1 UNION ALL
SELECT 1, '7/26/2010 2:15:00 PM' , -50 , -1 UNION ALL
SELECT 1, '7/27/2010 9:15:00 AM' , 25 , -1 UNION ALL
SELECT 1, '7/27/2010 12:00:00 PM', 196 , -1 UNION ALL
SELECT 1, '7/27/2010 2:15:00 PM' , -12.5, -1 UNION ALL
SELECT 1, '7/28/2010 9:15:00 AM' , 425 , -1 UNION ALL
SELECT 1, '7/28/2010 12:00:00 PM', -125 , -1 UNION ALL
SELECT 1, '7/28/2010 2:15:00 PM' , -12.5, -1 UNION ALL
SELECT 1, '7/29/2010 9:15:00 AM' , -37.5, -1 UNION ALL
SELECT 1, '7/29/2010 12:00:00 PM', -90 , -1 UNION ALL
SELECT 1, '7/29/2010 12:45:01 PM', -12.5, -1 UNION ALL
SELECT 1, '7/29/2010 12:45:02 PM', 0 , 0 UNION ALL
SELECT 1, '7/29/2010 12:45:03 PM', -75 , 1 UNION ALL
SELECT 1, '7/29/2010 2:15:00 PM' , 23 , 1;
Запрос:
WITH ranges AS (
SELECT
t.SID,
t.Sdate,
t.Units,
SdateStart = MAX(t0.Sdate)
FROM atable t
INNER JOIN atable t0
ON t0.SID = t.SID AND t0.Sdate < t.Sdate
AND t0.Profit = 0 AND t0.Units = 0
WHERE DATEPART(HH, t.Sdate) = 14
AND DATEPART(MI, t.Sdate) = 15
GROUP BY
t.SID,
t.Sdate,
t.Units
)
SElECT
r.SID,
r.Sdate,
Profit = SUM(t.Profit),
r.Units
FROM ranges r
INNER JOIN atable t ON t.SID = r.SID
AND t.Sdate BETWEEN r.SdateStart AND r.Sdate
GROUP BY
r.SID,
r.Sdate,
r.Units;
Выход:
SID Sdate Profit Units
----------- ----------------------- --------------------- -----------
1 2010-07-26 14:15:00.000 -175.00 -1
1 2010-07-27 14:15:00.000 33.50 -1
1 2010-07-28 14:15:00.000 321.00 -1
1 2010-07-29 14:15:00.000 -52.00 1