. . , UPDATE. , . , . , , APPROVAL_DAY, , . , .
CREATE TABLE
(
ID int,
APPROVAL_DT date,
DAY_DT date,
TRANS_COUNT int,
SALE_AMOUNT int,
DailyTransCount int,
DailySalesTotal int
)
INSERT INTO
SELECT 1,'2010-04-22','2010-04-27',2,260,0,0 UNION ALL
SELECT 1,'2010-04-22','2010-04-28', 1,40, 0,0 UNION ALL
SELECT 2,'2010-03-28','2010-04-02', 1,5, 0,0 UNION ALL
SELECT 2,'2010-03-28','2010-04-03', 5,10, 0,0 UNION ALL
SELECT 2,'2010-03-28','2010-04-04', 1,20, 0,0 UNION ALL
SELECT 3,'2010-04-25','2010-05-01', 6,10, 0,0 UNION ALL
SELECT 3,'2010-04-25','2010-05-02', 4,10, 0,0 UNION ALL
SELECT 4,'2010-06-01','2010-06-07', 1,5, 0,0
DECLARE @PreviousDay date; SET @PreviousDay = '29991231'
DECLARE @DailyTransCount int; SET @DailyTransCount = 0
DECLARE @DailySalesTotal int; SET @DailySalesTotal = 0
DECLARE @Group int; SET @Group = 0
UPDATE
SET DailyTransCount = 0,
DailySalesTotal = 0
UPDATE
SET @DailyTransCount = DailyTransCount = CASE WHEN APPROVAL_DT = @PreviousDay THEN @DailyTransCount + Trans_Count ELSE Trans_Count END,
@DailySalesTotal = DailySalesTotal = CASE WHEN APPROVAL_DT = @PreviousDay THEN @DailySalesTotal + SALE_AMOUNT ELSE SALE_AMOUNT END,
@PreviousDay = APPROVAL_DT
SELECT Y.ID, X.APPROVAL_DT, X.DAY_DT FROM
(SELECT DISTINCT(ID) FROM
LEFT JOIN ( SELECT ID, APPROVAL_DT, MIN(DAY_DT) AS DAY_DT FROM
WHERE DailyTransCount >= 10 OR DailySalesTotal >= 25
GROUP BY ID, APPROVAL_DT ) X ON X.ID = Y.ID
I have to explain a few things: I created two more columns at the end of my table. You will need to put this in the temp table (or the constant table) in order to push the totals. After I pulled all the totals into columns, it's just a choice to get the results. There is more detailed information about this method here . Please note that this is a FAST solution, but it is a little unsafe.