Addition to SQL query found

B

Barry

Here is a query that we had discussed a while back. I would like to know if
someone can adapt the SQL Aggregate Value query expression to additionally
yield:

leave SUM of NULL values in RESULT field if NULL values exist in 'QUAL'
field, but MAX the RESULT if QUAL is a value other than "ND" or "U", if no
NULL values exist in QUAL field for the same LAB_ID group.

Here is the database information from the previous query found.

Table of Sample Data:

SAMPLE DATE LAB_ID ANALYTE RESULT QUAL
MW-6 2/24/2006 711721 o-Xylene 2 ND
MW-6 2/24/2006 711721 o-Xylene 0.4
MW-5 2/24/2006 711722 o-Xylene 0.4 ND
MW-5 2/24/2006 711722 o-Xylene 9
MW-5 2/24/2006 711722 o-Xylene 1
MW-1 2/24/2006 711723 m+p-Xylene 2800
MW-1 2/24/2006 711723 o-Xylene 1900
MW-1 2/24/2006 711723 m+p-Xylene 1 ND
Duplicate 2/24/2006 711724 m+p-Xylene 2500
Duplicate 2/24/2006 711724 o-Xylene 1700

SQL query expression:

SELECT X1.LAB_ID, 'max_of' AS aggregate_type,
MAX(IIF(X1.QUAL IS NULL, NULL, X1.[RESULT])) AS aggregate_value
FROM Xylenes AS X1
WHERE NOT EXISTS (
SELECT *
FROM Xylenes AS X2
WHERE X2.LAB_ID = X1.LAB_ID
AND X2.QUAL IS NULL
)
GROUP BY X1.LAB_ID
UNION ALL SELECT X1.LAB_ID, 'sum_of',
SUM(IIF(X1.QUAL IS NULL, X1.[RESULT], NULL))
FROM Xylenes AS X1
WHERE EXISTS (
SELECT *
FROM Xylenes AS X2
WHERE X2.LAB_ID = X1.LAB_ID
AND X2.QUAL IS NULL
)
GROUP BY X1.LAB_ID
ORDER BY 1;

Result:

LAB_ID aggregate_type aggregate_value
711721 sum_of 0.4
711722 sum_of 10
711723 sum_of 4700
711724 sum_of 4200
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top