Code:
SELECT Sottoregione, Sottodivisione, NationalStationID, Region, Year, Month, Day, SampleDepth, sum(iif(Determinand_Nutrients='Temperature',Concen tration,Null)) AS Temperature, sum(iif(Determinand_Nutrients='Salinity',Concentra tion,null)) AS Salinity, sum(iif(Determinand_Nutrients='Chlorophyll a',Concentration,null)) AS Chl_a
FROM D5_2015_2017 AS a
WHERE Abs(0.5-SampleDepth)=
(
SELECT Min(Abs(0.5-SampleDepth))
FROM D5_2015_2017 b
WHERE a.NationalStationId=b.NationalStationId
and a.Year=b.Year
and a.Month=b.Month
and a.Day=b.Day
and b.Determinand_Nutrients in ('Temperature','Salinity','Chlorophyll a')
)
AND a.Determinand_Nutrients in ('Temperature','Salinity','Chlorophyll a') AND a.NationalStationId='50530'
GROUP BY a.Sottoregione, a.Sottodivisione, a.NationalStationID, a.Region, a.Year, a.Month, a.Day, a.SampleDepth;
I think there may be a couple of things you can do on the basis the code highlighted in red is your subquery
1. Change it to a aggregate query and join on the fields
Code:
(
SELECT Min(Abs(0.5-SampleDepth)) As minDepth
FROM D5_2015_2017
WHERE Determinand_Nutrients in ('Temperature','Salinity','Chlorophyll a')
GROUP BY NationalStationId, Year, Month, Day
)
Your query then becomes
Code:
SELECT Sottoregione, Sottodivisione, NationalStationID, Region, Year, Month, Day, SampleDepth, sum(iif(Determinand_Nutrients='Temperature',Concen tration,Null)) AS Temperature, sum(iif(Determinand_Nutrients='Salinity',Concentra tion,null)) AS Salinity, sum(iif(Determinand_Nutrients='Chlorophyll a',Concentration,null)) AS Chl_a
FROM D5_2015_2017 AS a INNER JOIN
(
SELECT NationalStationId, Year, Month, Day, Min(Abs(0.5-SampleDepth)) As minDepth
FROM D5_2015_2017
WHERE Determinand_Nutrients in ('Temperature','Salinity','Chlorophyll a')
GROUP BY NationalStationId, Year, Month, Day
) b
ON a.NationalStationId=b.NationalStationId
and a.Year=b.Year
and a.Month=b.Month
and a.Day=b.Day
and Abs(0.5-SampleDepth)=b.minDepth
WHERE a.Determinand_Nutrients in ('Temperature','Salinity','Chlorophyll a') AND a.NationalStationId='50530'
GROUP BY a.Sottoregione, a.Sottodivisione, a.NationalStationID, a.Region, a.Year, a.Month, a.Day, a.SampleDepth;
2. The other thing to do is turn this query into a crosstab with 'Temperature','Salinity','Chlorophyll a' as your column headings
A couple of things on performance, ensure all fields that are grouped and/or joined on are indexed. You might also want to consider combining Year, Month, Day into a single date field
Finally Year, Month, Day are all reserved words, use them as field names at your peril.
EDIT: Sorry should have said - you will not be able to see this query in the query window because of the non standard join 'and Abs(0.5-SampleDepth)=b.minDepth'. However you could move this one line out of the join and put into the WHERE clause, probabaly won't have much effect on performance