I am coding a dashboard, and I need to pull some data out of Microsoft SQL Server.
For a simple example, I have three tables, one master Category table, and two tables containing values linked to the Category table via a primary/foreign key relationship (Blue and Green value tables).
Using Microsoft SQL Sever (t-sql), I wish to total (sum) the values in the two value tables, grouped by the common category found in the category table.
Category Table
CategoryID (PK) | CategoryName
1 | Square
2 | Circle
Blue Table
BlueID (PK) | CategoryID (FK) | BlueValue | BlueMonth | BlueYear
1 | 1 | 10 | 6 | 2012
2 | 1 | 20 | 12 | 2012
3 | 2 | 5 | 6 | 2012
4 | 2 | 9 | 12 | 2012
5 | 1 | 12 | 6 | 2013
6 | 1 | 21 | 12 | 2013
7 | 2 | 4 | 6 | 2013
8 | 2 | 8 | 12 | 2013
Green Table
GreenID (PK)| CategoryID (FK) | GreenValue| GreenMonth| GreenYear
1 | 1 | 3 | 6 | 2012
2 | 1 | 6 | 12 | 2012
3 | 2 | 2 | 6 | 2012
4 | 2 | 7 | 12 | 2012
5 | 1 | 2 | 6 | 2013
6 | 1 | 5 | 12 | 2013
7 | 2 | 4 | 6 | 2013
8 | 2 | 8 | 12 | 2013
If I use the following SQL, I get the results I expect.
SELECT
[Category].[CategoryName],
SUM([Green].[GreenValue]) AS [GreenTotal]
FROM
[Category]
LEFT JOIN
[Green] ON [Category].[CategoryID] = [Green].[CategoryID]
GROUP BY
[Category].[CategoryName]
Results:
CategoryName | GreenTotal
Square | 16
Triangle | 21
However, if I add the Blue table, to try and fetch a total for BlueValue as well, my obviously incorrect T-SQL gives me unexpected results.
SELECT
[Category].[CategoryName],
SUM([Green].[GreenValue]) AS [GreenTotal],
SUM([Blue].[BlueValue]) AS [BlueTotal]
FROM
[Category]
LEFT JOIN
[Green] ON [Category].[CategoryID] = [Green].[CategoryID]
LEFT JOIN
[Blue] ON [Category].[CategoryID] = [Blue].[CategoryID]
GROUP BY
[Category].[CategoryName]
Incorrect Results:
CategoryName | GreenTotal | BlueTotal
Square | 64 | 252
Triangle | 84 | 104
The results all seem to be out by a factor of 4, which is the total number of rows in each value table for each category.
I am aiming to see the following results:
CategoryName | GreenTotal | BlueTotal
Square | 16 | 63
Triangle | 21 | 26
I would be over the moon if someone could tell me what on earth I am doing wrong?
Thanks, Mark.