Hi,
I'm slowly but surely learning SQL etc and was hoping someone could advise on the following:
I have these two tables:
Using the [Rate] in 'SplitMatrix' I need to return the following From 'Data'
Here is my current Query:
I'm wondering whether this is the correct way to structure the Query or is there an easier way? (easier = fewer lines/more efficient)
I'm slowly but surely learning SQL etc and was hoping someone could advise on the following:
I have these two tables:
Excel 2010 | |||||
---|---|---|---|---|---|
A | B | C | |||
1 | ID | Site | Cost | ||
2 | 1 | A | £100.00 | ||
3 | 2 | B | £200.00 | ||
4 | 3 | C | £500.00 | ||
5 | 4 | D | £1,000.00 | ||
6 | 5 | E | £100.00 | ||
Data |
Excel 2010 | ||||||
---|---|---|---|---|---|---|
A | B | C | D | |||
1 | ID | Site1 | Site2 | Rate | ||
2 | 1 | A | E | 0.25 | ||
3 | 2 | A | C | 0.5 | ||
4 | 3 | A | D | 0.25 | ||
5 | 4 | B | E | 0.8 | ||
6 | 5 | B | D | 0.2 | ||
SplitMatrix |
Using the [Rate] in 'SplitMatrix' I need to return the following From 'Data'
Excel 2010 | |||||
---|---|---|---|---|---|
G | H | I | |||
4 | ID | Site | Cost | ||
5 | 3 | C | £550.00 | ||
6 | 4 | D | £1,065.00 | ||
7 | 5 | E | £285.00 | ||
Query Result |
Here is my current Query:
Code:
SELECT C.Site, SUM(C.Cost) As Total
FROM
(SELECT A.Site, A.Cost
FROM Data As A
LEFT JOIN SplitMatrix As B
On A.Site = B.Site1
WHERE B.Site1 IS NULL
UNION ALL
SELECT A.Site2 As Site, (B.Cost * A.Rate) As Cost
FROM SplitMatrix As A
LEFT JOIN Data As B
On A.Site1 = B.Site
WHERE B.Site <> NULL) As C
GROUP BY C.Site
I'm wondering whether this is the correct way to structure the Query or is there an easier way? (easier = fewer lines/more efficient)