Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
ID + Avg    + average 3 consecutive 
A  +  60.0  +    --             +
B  +  62.0  +    --             +
C  +  63.0  +    61.7           + <- Average of (ABC)
D  +  59.0  +    61.3           + <- Average of (BCD)
E  +  58.0  +    60.0           + <- Average of (CDE)
F  +  60.0  +    59.0           + <- Average of (DEF)
G  +  61.0  +    59.7           + <- Average of (EFG)


In my report i am looking for this result (3 rd column)
i have the 1st and 2nd column i cannot make the third column(average 3 consecutive ) in crystal report.

Please help...

Thanks in advance
Posted
Updated 20-May-15 3:17am
v4

1 solution

SQL
DECLARE @DATA TABLE 
(
    ID NCHAR(1) NOT NULL,
    AVARAGE FLOAT NOT NULL
)

INSERT  @DATA(ID, AVARAGE)
	SELECT  'A', 60.0
	UNION ALL
	SELECT  'B', 62.0
	UNION ALL
	SELECT  'C', 63.0
	UNION ALL
	SELECT  'D', 59.0
	UNION ALL
	SELECT  'E', 58.0
	UNION ALL
	SELECT  'F', 60.0
	UNION ALL
	SELECT  'G', 61.0

;
WITH ORDERED_TABLE AS
(
	SELECT ID, AVARAGE, ROW_NUMBER() OVER (ORDER BY ID) AS ROWNUMBER FROM @DATA
)

SELECT 
	OT_OUT.ID, 
	OT_OUT.AVARAGE,
	CASE WHEN OT_OUT.ROWNUMBER < 3
		THEN NULL
		ELSE
			(
				SELECT AVG(AVARAGE) 
    				FROM ORDERED_TABLE AS OT_IN
    				WHERE OT_IN.ROWNUMBER IN (OT_OUT.ROWNUMBER, OT_OUT.ROWNUMBER - 1, OT_OUT.ROWNUMBER - 2)
			)
	END AS CONSECUTIVE_AVARAGE
FROM ORDERED_TABLE AS OT_OUT

WITH ORDERED_TABLE AS, declares a CTE where you add to every row a row-number so you can say which hare the previous two rows to use with average computation...
The second part is a simple query based on this CTE to do the computation...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900