Question : Access SQL: Self Join with Multiple Criteria

I need to calculate the incremental operating profit, organized by the technology used using a table that stores the profit for a given technology and a given deployment location.  The incremental profit cannot be negative for a given location year over year, and if it is, it is set to zero.

I am using a self query that has a left join, since a deployment location may go up in 2010, but not exist in 2009.  I want to calculate the incremental OP values (year over year) for a given technology and location, and make sure that they are non-negative or zero, and then sum them up over all locations for a given technology.

What I think I want is included, but it doesn't seem to work.  I don't know if it is possible to have multiple criteria in a ON statement.  When I try this, I get a type mismatch on the b.ValueYear=a.ValueYear-1 statement.  I don't think that is the actual problem, though.  I have looked at somewhat similar problems, but nothing seems to fit.

I appreciate the help.
Code Snippet:
1:
2:
3:
4:
SELECT a.ValueYear, a.Technology, format(sum(switch(NZ(a.OPAnnualOP,0)-NZ(b.OPAnnualOP,0)>=0,NZ(a.OPAnnualOP,0)-NZ(b.OPAnnualOP,0),0=0,0)),"0.000") AS IncrementalOP
FROM qryYearlyOPSavings AS a LEFT JOIN qryYearlyOPSavings AS b ON b.ValueYear=a.ValueYear-1 AND a.Opportunity=b.Opportunity AND a.Technology=b.Technology
WHERE a.ValueYear > (SELECT min(ValueYear) FROM qryYearlyOPSavings)
GROUP BY a.ValueYear, a.Technology;

Answer : Access SQL: Self Join with Multiple Criteria

You are absolutely right. I somehow thought I has removed the possibility of Null, but of course in a LEFT JOIN you will get Null values on the right side... And I did drop the field Opportunity somewhere along the copy-pasting. I'm glad you caught both problems and made it work.

Regarding several action queries stored in one object, I also regret this limitation in Access, but then you can always run a series of queries using a macro (for those who don't want to get into Visual Basic), so it was never a priority.

The fundamental issue about the incredibly long execution time is that you cannot index on an expression, nor can Jet index an expression temporarily in the execution plan. This makes any condition based on calculations very hard to handle.

The temporary table solution however isn't just a "hack". It's used daily in all banks to handle end-of-day closing queries, for example. In terms of maintenance and traceability, it makes sense, and it's also very efficient. The only slight downside in Access is that you will have to compact a little more often.

Cheers!
(°v°)
Random Solutions  
 
programming4us programming4us