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. ?

Answers


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 ?


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

Need Your Help

How to make round custom Tabbar, in iPhone?

iphone ios objective-c xcode uitabbar

I want to make round custom TabBar. when click on the tab it will move one forward and the second tab will come on its place.

16-bit obj files VC++

visual-c++ compilation bootloader 16-bit object-files

How do I compile my VC++ project to a 16-bit flat object file for use in my bootloader I am working on?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.