How do I exclude rows when an incremental value starts over?

空扰寡人 提交于 2019-12-06 03:35:45

Not sure what ModuleID was supposed to be used, but I guess you're looking for something like this:

select min (instanceDate), [moduleID], avg([iResult])
from (
  select *,row_number() over (partition by [moduleID] order by instanceDate) as RN
  from Table1
) X
group by [moduleID], RN - [interactionNum]

The idea here is to create a running number with row_number for each moduleid, and then use the difference between that and InteractionNum as grouping criteria.

Example in SQL Fiddle

Here is my solution, although it should be said, I think @JamesZ answer is cleaner.

I created a new field called newinstance which is 1 wherever your instanceNumber is 1. I then created a rolling sum(newinstance) called rollinginstance to group on.

Change the last select to SELECT * FROM cte2 to show all the fields I added.

IF OBJECT_ID('tempdb..#tmpData') IS NOT NULL
    DROP TABLE #tmpData

CREATE TABLE #tmpData (recordID INT, instanceDate DATETIME, moduleID INT, iResult INT, interactionNum INT)

INSERT INTO #tmpData
SELECT 1356,'10/6/15 16:14',1,68,1 UNION
SELECT 1357,'10/7/15 16:22',1,100,2 UNION
SELECT 1434,'10/9/15 16:58',1,52,1 UNION
SELECT 1435,'10/11/15 17:00',1,60,2 UNION
SELECT 1436,'10/15/15 16:57',1,100,3 UNION
SELECT 1437,'10/15/15 16:59',1,100,4

;WITH cte1 AS
(
    SELECT *,
           CASE WHEN interactionNum=1 THEN 1 ELSE 0 END AS newinstance,
           ROW_NUMBER() OVER(ORDER BY recordID) as rowid
    FROM #tmpData
), cte2 AS
    (
        SELECT *,
               (select SUM(newinstance) from cte1 b where b.rowid<=a.rowid) as rollinginstance
        FROM cte1 a
    )

SELECT MIN(instanceDate) AS instanceDate, moduleID, AVG(iResult) AS iResult
FROM cte2
GROUP BY moduleID, rollinginstance
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!