I there a better way to write this query? I feel sure it can be done in one statement with joins, but I couldn't get it, and I'm afraid I've made it too slow. What suggestions do you have? I'm running it in SQL Server 2000 (yeah, I know, upgrade is coming).
Basically, I want to match estimated and actual costs, but sometimes the estimate is done on 1 cost center, and the actual costs are set to another cost center (hence the possibility of having null in est or act. I want to get all possible combinations for that job.
ALTER view [dbo].[JobCost_EstVsAct] --SELECT * FROM JobCost_EstVsAct Where jobnumber = '122773'
as
SELECT JobNumber, CostCenter, sum(Amount) as Est, sum(cost) as Act
FROM
(
SELECT JobNumber, CostCenter, Amount, 0 as cost
FROM Avanti_ActiveJobBudgets AJB
UNION
SELECT jobnumber, costcentre as CostCenter, 0 as Est, cost as Act
FROM Avanti_ActiveCostDetails
) temp
--where cost + Amount > 0 This line is a bug
GROUP by JobNumber, CostCenter
HAVING sum(Amount) + sum(cost) > 0 --bug correction
'' as Estrather thannull as Est? I think you are forcing an unnecessary cast. I do not think a join will help. Algorithmically your query is pretty fast; the only potential concern is the elimination of duplicates performed byUNION. If not for that, then your query would be potentially linear. 'Join' is not a magic keyword that makes everything fast; neither is 'index'. \$\endgroup\$null as Estis better? I just thought I could do this same thing with a join that would not bring in the duplicates in the first place. \$\endgroup\$select '' union select 1;- you get0and1. It converts''to0which is surprising - might as well write0instead of''. If you did want an empty string, thennullis better (unless 0 makes even better sense). This way you can reuse this view for further computation or you can plug it into a report. Most reporting tools allow you to replace a null with whatever string or value you wish. \$\endgroup\$0 as cost. I do not like having an implicit cast where one is not necessary. For example: this creates problems (but only at run time):create procedure foo as begin select 1 union select 'a' end. There is no compiler that will catch problems for you. It is a general principle of programming - keep things simple and readable. If you want0then type0. Just because you have memorized the implicit cast table i.msdn.microsoft.com/dynimg/IC170617.gif does not mean that the next programmer will or should. Other than that it looks ok to me. \$\endgroup\$