Not sure if the title makes sense but I'll give this a shot.
Basically I have a report where I throw a bunch of data into a temp table and then display it on a webpage. The totals for this report need to be a weighted average but some data in the table throws this average off.
Here's an example of the data set in the temp table
CustomerNo CountryCode qJAN rJAN gJAN qFEB rFEB gFEB
IDS1 ID 1500 0 0 1500 0 0
ID18J ID 8000 15 120000 8000 15 120000
ID21 ID 3000 0 0 0 0 0
ID22J ID 9000 0 0 12000 0 0
ID22S ID 9500 0 0 0 0 0
ID22S ID 9500 0 0 0 0 0
ID31S ID 3000 0 0 0 0 0
Where qCOL is quantity, rCOL is rate and gCOL is gross (quantity * rate).
Now values are only to count towards the country's total if there is a quantity and rate. The query I have been using is as follows:
SELECT CASE SUM(qJAN) WHEN 0 THEN 0 ELSE SUM(gJAN) / SUM(qJAN) END AS JAN,
CASE SUM(qFEB) WHEN 0 THEN 0 ELSE SUM(gFEB) / SUM(qFEB) END AS FEB,
...
CASE(SUM(qJAN) + SUM(qFEB) + ... )
WHEN 0 THEN 0
ELSE
(SUM(gJAN) + SUM(gFEB) + ... ) / (SUM(qJAN) + SUM(qFEB) + ...) END AS TOT
FROM table
WHERE CountryCode = N'ID'
The above query returns the following weighted averages for JAN and FEB respectively: 3.24 and 4.90 both of which are wrong. The correct result would be 15.00 for both.
The problem is that the above takes the quantities that have no rates into account.
I can get around this by using subqueries but what I came up with started to get out of control and will really bog things down:
SELECT CASE
(SELECT SUM(qJAN) FROM table WHERE CountryCode = N'ID' AND rJAN <> 0)
WHEN 0 THEN 0 ELSE
SUM(gJAN) /
(SELECT SUM(qJAN) FROM table WHERE CountryCode = N'ID' AND rJAN <> 0)
END AS JAN,
CASE
(SELECT SUM(qFEB) FROM table WHERE CountryCode = N'ID' AND rFEB <> 0)
WHEN 0 THEN 0 ELSE
SUM(gFEB) /
(SELECT SUM(qFEB) FROM table WHERE CountryCode = N'ID' AND rFEB <> 0)
END AS FEB,
...
CASE
(
(SELECT SUM(qJAN) FROM table WHERE CountryCode = N'ID' AND rJAN <> 0) +
(SELECT SUM(qFEB) FROM table WHERE CountryCode = N'ID' AND rFEB <> 0) +
...
)
WHEN 0 THEN 0 ELSE
(SUM(gJAN) + SUM(gFEB) + ...) /
(
(SELECT SUM(qJAN) FROM table WHERE CountryCode = N'ID' AND rJAN <> 0) +
(SELECT SUM(qFEB) FROM table WHERE CountryCode = N'ID' AND rFEB <> 0) + ...
) END AS TOT
This returns the correct totals but as you can see it gets ugly fast. All these subqueries are going to kill performance.
Is there a simpler way to get the result I'm looking for? I feel like there must be but I'm completely brain-locking on this.
Thanks.