HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

SQL Group and Filter - Refining down a search including Dates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
grouprefiningsqlsearchdatesfilterdownincludingand

Problem

The below process is designed to pick out only AsbestosUPRNs and get the lowest OverallRiskCategory where they have the newest SurveyDate. I just wanted to ensure this is the best way, it seems neat now though as well as second code, which in reality is the same thing, based on two tables.

SELECT 
AsbestosUPRN, 
MIN(OverallRiskCategory) AS OverallRiskCategory, 
MAX(SurveyDate) AS SurveyDate
FROM TblAsbestos 
GROUP BY 
AsbestosUPRN


Two Table version:

SELECT
p.UCARN, 
MAX(a.OverallRiskCatNumberical) as OverallRiskCatNumberical, 
MAX(a.SurveyDate) AS SurveyDate
FROM TblAsbestos AS a
INNER JOIN TblProperty AS p
ON p.UPRN = a.AsbestosUPRN 
GROUP BY 
p.UCARN

Solution

Overall, that looks good. You've followed basic SQL styling rules, capitalising keywords for example, and the both queries are consistent. Anyone looking at that is going to struggle to find things to complain about.

A couple little things, the first AS in your second query isn't capitalised. I would change it to AS to make the query more consistent.

I'd say that the table aliases in the second query should be more meaningful than just a and p. Other than that, good job.

I would recommend using the first query, it avoids the join and, presumably, returns the same correct results.

Context

StackExchange Code Review Q#62401, answer score: 6

Revisions (0)

No revisions yet.