I hope you don't mind me poking my nose in here after other people have been answering...
ldejesuspr,
your query looks fine. Maybe it would help to review how GROUP BY works? Let me give an example. Here's a table called Salaries:
[tt]EmpID Dept Salary
1 1 45000
2 1 90000
3 1 60000
4 2 16000
5 2 24000
6 2 22500
7 3 135000
8 3 127500[/tt]
I know which department I want to work in! Let's say we want to see the minimum, maximum, average, and sum of each department's salaries, with the number of salaries paid out:
Code:
SELECT
Dept,
Lowest = Min(Salary),
Highest = Max(Salary),
Average = Avg(Salary),
DeptCost = Sum(Salary),
Headcount = Count(*)
FROM Salaries
GROUP BY Dept
---- Result set:
Dept Lowest Highest Average DeptCost Headcount
1 45000 90000 65000 195000 3
2 16000 24000 20833 62500 3
3 127500 135000 131250 262500 2
The fields in the GROUP BY clause let the query engine know across what span it will do the aggregate functions. You don't get one row with 16000 for the Lowest... you get one row per unique combination of values in the fields in the group by clause. Since there is only one field in it, you get as many rows as there are unique Depts in the Salaries table.
If instead, you just want the values for everything in the table, you have to remove the departments from the SELECT and GROUP BY clauses:
Code:
SELECT
Lowest = Min(Salary),
Highest = Max(Salary),
Average = Avg(Salary),
DeptCost = Sum(Salary),
Employees = Count(*)
FROM Salaries
---- Result set:
Lowest Highest Average DeptCost Headcount
16000 135000 65000 520000 8
Note that if you include the EmpID in the SELECT and GROUP BY clauses, you get something not very spectacular:
Code:
SELECT
EmpID,
Dept,
Lowest = Min(Salary),
Highest = Max(Salary),
Average = Avg(Salary),
DeptCost = Sum(Salary),
Employees = Count(*)
FROM Salaries
GROUP BY
EmpID,
Dept
---- Result set:
EmpID Dept Lowest Highest Average DeptCost Headcount
1 1 45000 45000 45000 45000 1
2 1 90000 90000 90000 90000 1
3 1 60000 60000 60000 60000 1
4 2 16000 16000 16000 16000 1
5 2 24000 24000 24000 24000 1
6 2 22500 22500 22500 22500 1
7 3 135000 135000 135000 135000 1
8 3 127500 127500 127500 127500 1
You get one row for each unique combination of EmpID and Dept... and since each row in the source data is unique for these two fields, you get one row for each.
I hope this helps!
-------------------------------------
A sacrifice is harder when no one knows you've made it.