CREATE FUNCTION [dbo].[fn_GetSurfaceFieldAggregateDIFF]
( 
	@surfaceItemId INT
	,@actionValue VARCHAR(255)
)
RETURNS INT
AS
BEGIN
DECLARE @returnVal INT

DECLARE @tempValues TABLE (rowId INT,val DECIMAL(18,2))

INSERT INTO @tempValues 
SELECT	ROW_NUMBER() OVER(ORDER BY F.recId) rowId
		,CASE F.surfaceFieldTypeId 
			WHEN 4
			THEN D.surfaceFieldValueNum
			WHEN 5
			THEN D.surfaceFieldValueDecimal
			WHEN 14 
				THEN
				CASE WHEN F.actionType = 8
					THEN CASE F.[action]
						WHEN 12
							THEN CAST(dbo.fn_GetSurfaceFieldAggregateAverage(@surfaceItemId,F.actionValue,0) AS VARCHAR(MAX))
						WHEN 14
							THEN CASE WHEN F.controlledValue = '75' THEN CAST(dbo.fn_GetSurfaceFieldAggregateDistinctionCount(@surfaceItemId,F.actionValue, 0) AS VARCHAR(MAX)) 
												ELSE CAST(dbo.fn_GetSurfaceFieldAggregateDistinctionCount(@surfaceItemId,F.actionValue, DEFAULT) AS VARCHAR(MAX)) END
						WHEN 15
							THEN CAST(dbo.fn_GetSurfaceFieldAggregateSUM(@surfaceItemId,F.actionValue) AS VARCHAR(MAX))
						WHEN 16
							THEN CAST(dbo.fn_GetSurfaceFieldAggregateDIFF(@surfaceItemId,F.actionValue) AS VARCHAR(MAX))
						END
					END
			END val
FROM	pal_SurfaceField F
		JOIN pal_SurfaceFieldData D
			ON D.surfaceFieldID = F.recId
WHERE	D.surfaceItemId = @surfaceItemId
		AND F.recId IN (SELECT splitdata FROM SplitString(@actionValue,'|'))
ORDER BY F.sequence
		
SELECT TOP 1 @returnVal = (t2.val - t1.val)
FROM @tempValues t1 CROSS JOIN
     @tempValues t2
WHERE t1.rowId <> t2.rowId


RETURN	@returnVal

END
