Cannot figure out why I'm getting this error: Msg 102, Level 15, State 1, Line 74 Incorrect syntax near ')'

FSI 0 Reputation points
2025-04-24T21:13:12.1866667+00:00

Pretty new to SQL, I keep getting an error on the final bracket at the end of the code, but I can't figure it out. Anyone see any reasons?

;with cte as 

(

SELECT SampleID

,SetpointID

,CDPercentDiff

,AuditID 

,pointrn = ROW_NUMBER()

	OVER (

		partition by SetpointID, AuditID

		order by AuditID asc

			,SetpointID asc

			,SampleID desc

		)

FROM [FSIStandards].[dbo].[Audit_Test_Results_backup]

WHERE AuditID in

	(

	SELECT [AuditID]

	FROM [FSIStandards].[dbo].[Audit_Tests_backup]

	WHERE Bench_QC_ID = 'CAL_006' 

		AND	[PassFail] = 'Fail'

	)

)

SELECT *

From

(

SELECT DISTINCT [MaxDiff] =

	MAX(ABS([CDPercentDiff]))

	OVER (Partition by AuditID order by AuditID)

	,[AuditID]

FROM 

	

	(

		SELECT SampleID

			,SetpointID

			,CDPercentDiff

			,AuditID

			,pointrn



		FROM cte

		WHERE 

				 AuditID IN

					(

					SELECT [AuditID]

					FROM [FSIStandards].[dbo].[Audit_Tests_backup]

					where Bench_QC_ID = 'CAL_006' 

					AND	[PassFail] = 'Fail'

					)

				AND pointrn = 1

				OR pointrn = 2

	 		)

) AS [MaxDiff]

WHERE [MaxDiff] < .15

SQL Server Database Engine
{count} votes

1 answer

Sort by: Most helpful
  1. David Fouché 0 Reputation points
    2025-04-25T00:43:11.2733333+00:00

    -- I suggest you to break down your query in multiple cte for better clarity.

    ;with cte as

    (

    SELECT SampleID

    ,SetpointID

    ,CDPercentDiff

    ,AuditID

    ,pointrn = ROW_NUMBER()

    OVER (
    
    	partition by SetpointID, AuditID
    
    	order by AuditID asc
    
    		,SetpointID asc
    
    		,SampleID desc
    
    	)
    FROM [FSIStandards].[dbo].[Audit_Test_Results_backup]
    
    WHERE AuditID in
    
    

    (

    SELECT [AuditID]

    FROM [FSIStandards].[dbo].[Audit_Tests_backup]

    WHERE Bench_QC_ID = 'CAL_006'

    AND	[PassFail] = 'Fail'
    ```)
    ```)
    
    SELECT *
    
    From
    
    (
    
    SELECT DISTINCT [MaxDiff] =
    
    

    MAX(ABS([CDPercentDiff]))

    OVER (Partition by AuditID order by AuditID)

    ,[AuditID]

    
    

    (

    SELECT SampleID
    
    	,SetpointID
    
    	,CDPercentDiff
    
    	,AuditID
    
    	,pointrn
    
    FROM cte
    
    WHERE 
    
    		 AuditID IN
    
    			(
    
    			SELECT [AuditID]
    
    			FROM [FSIStandards].[dbo].[Audit_Tests_backup]
    
    			where Bench_QC_ID = 'CAL_006' 
    
    			AND	[PassFail] = 'Fail'
    
    			)
    
    		AND pointrn = 1
    
    		OR pointrn = 2
    
    	)
    ``````) AS [MaxDiff]
    
    WHERE [MaxDiff] < .15
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.