I'm trying to get a Top 3 from a table in MS Access with SQL but I can't wrap my head around it.
My_table:
ControlPoint / Points / Date / ByWho
---------------------------------------------
FlagA 6 202305 DepartmentA
FlagB 5 202305 DepartmentA
FlagC 1 202305 DepartmentA
FlagA 3 202305 DepartmentA
FlagD 3 202305 DepartmentA
FlagA 1 202305 DepartmentB
FlagA 3 202304 DepartmentA
The user chooses a "DepartamentX" and "Date". After that I want to show the top 3 "ControlPoint" according to the SUM of points. So in this case for "Date: 202305" and "DepartmentA" the result would be = FlagA 9 FlagB 5 FlagD 3
So what is the best way to do this? By sorting as top 3 direct in SQL or make an array in PHP and then sort it? And then how?
I'm using ODBC.
EDIT: I used the code below to get me all of the rows, now I just need to figure out how to sum the "Points" to correct "ControlPoint" and then sort it by Top 3 somehow.
"SELECT ControlPoint,Points FROM My_table WHERE Date = '{$date}' AND ByWho = '{$bywho}'"
while(odbc_fetch_row($result)){
$array = odbc_result_all($result);
}
The code above didn't do the trick, still stuck. Safe to say, I'm going insane over this problem, any help is much appreciated!
Try this:
SELECT TOP 3 ControlPoint , SUM(Points) AS TOTAL_POINTS
FROM My_table
GROUP BY ByWho , Date , ControlPoint
HAVING ByWho ='{$bywho}' AND Date= '{$date}'
ORDER BY SUM(Points) DESC