I'm trying to fetch the first entry of each group after the custom ORDER BY but don't know how to select that first entry of each group. The groups should be ordered by the @team if exist, otherwise other team else NULL.
SELECT t1.*
FROM tbl t1
INNER JOIN tbl2 t2 ON t2.group_id = t1.group
WHERE t2.region = @region
ORDER BY
CASE
WHEN team=@team THEN 1
WHEN team is NOT NULL THEN 2
WHEN team is NULL THEN 3
END
Content of tbl
id group team
1 1 AA
2 1 BB
3 2 AA
4 2 CC
5 3 BB
6 3 NULL
7 4 NULL
Expected result when @team=AA
id group team
1 1 AA
3 2 AA
5 3 BB
7 4 NULL
Expected result when @team=BB
id group team
2 1 BB
3 2 AA
5 3 BB
7 4 NULL