sql group by values from two columns
City | Person City | Person -------------- ------------- C | Fanie D | Jan C | Johannes D | Maria C | Anna to J | Frik D | Jan C | Anna D | Maria C | Fanie J | Frik C | Johannes
I want ^ table to be like this one ^.
I have tried to say Select * FROM TableA GROUP BY City ='D', City = 'J' City = 'C' but then the names are not in the order as shown above? How would I achieve this? Or how do you croup by a column value and sort the names. ?
For customized sorting, or sorting based on some rule, one can use case statement in order by clause in following way and execute it
Select * FROM TableA order by case when city ='D' then 1 when city ='J' then 2 else 3 end, Person
Can you try this ?
SELECT City, Person FROM TableA WHERE City IN ('C', 'D', 'J') ORDER BY (CASE City WHEN 'D' THEN 1 WHEN 'J' THEN 2 WHEN 'C' THEN 3 ELSE 4 END), Person;
select * from TableA ORDER BY City,Person
This should work if you want to sort by City then by Person, but from your output I can't see anykind of sorting.
i dont know why you need to do this i hope this will help you!, i used the CASE function of MySQL the solution that i provide is WHEN the City is equals to 'D' it will be the first who sort then if City = 'C' then it will be the second ELSE it will be the last
SELECT * FROM TableA GROUP BY City,Person ORDER BY CASE WHEN City = 'D' THEN 1 WHEN 'C' THEN 2 ELSE 3 END