I've got two tables similar to these:
TABLE1
PC Date Num Name ID
8901 01/03/2013 5099 AAA 11
8901 01/03/2013 5099 AAA 11
8901 01/03/2013 5099 AAA 11
8901 02/03/2013 5099 AAA 12
8902 03/03/2013 5099 AAA 13
8903 04/03/2013 5099 AAA 14
TABLE2
PC Date Num Name ID Bar2
8901 01/03/2013 5099 AAA 11 3
8901 01/03/2013 5099 AAA 11 2
8901 01/03/2013 5099 AAA 11 9
8901 02/03/2013 5099 AAA 12 3
8902 03/03/2013 5099 AAA 13 4
8903 04/03/2013 5099 AAA 14 5
And this query:
SELECT TABLE1.PC, TABLE1.Date, TABLE1.Num, TABLE1.Name, COUNT(*), SUM(TABLE2.Bar2)
FROM TABLE1, TABLE2
WHERE TABLE1.ID = TABLE2.ID
GROUP BY TABLE1.PC, TABLE1.Date, TABLE1.Num, TABLE1.Name
ORDER BY TABLE1.PC, TABLE1.Date
The result is:
PC Date Num Name COUNT SUM
8901 01/03/2013 0:00 5099 AAA 9 42
8901 02/03/2013 0:00 5099 AAA 1 3
8902 03/03/2013 0:00 5099 AAA 1 4
8903 04/03/2013 0:00 5099 AAA 1 5
So, it sums and then it multiplies by the nº of entries ((3+2+9)*3 = 42).
What am I doing wrong? thanks!!
It is not exactly clear what you want as the desired result, but you can use a subquery to get the Total Sum:
SELECT t1.PC,
t1.Date,
t1.Num,
t1.Name,
COUNT(*),
t2.Total
FROM TABLE1 t1
INNER JOIN
(
SELECT SUM(Bar2) Total, ID
FROM TABLE2
GROUP BY ID
) t2
ON t1.ID = t2.ID
GROUP BY t1.PC, t1.Date, t1.Num, t1.Name, t2.Total
ORDER BY t1.PC, t1.Date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.