I have a output from select as below
| s.no | user_id | user_type | user_group | prefix | fname | mname | lname | suffix |nick_name | company | department | designation_title | industry | dob | nationality | passport_number | photograph | mobile | email | permanent_address | temporary_address | bbm_p |t_number_arrival | departure_date_time | depart_airlines | flight_number_departure |
| 17 | 0 | Husband | 23 | sasas | asd | | | | | | | | |0000-00-00 | | | | 0 | asdas | | sadx | asd| 0000-00-00 00:00:00 | | |
| 18 | 0 | wife | 23 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 19 | 0 | kid1 | 23 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 20 | 0 | kid2 | 23 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 21 | 0 | kid3 | 23 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 22 | 0 | kid4 | 23 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 23 | 0 | Husband | 24 | sasas | asd | | | | | | | | | 0000-00-00 | | | | 0 | asdas | | sadx | asd| 0000-00-00 00:00:00 | | |
| 24 | 0 | wife | 24 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | | | 0000-00-00 00:00:00 | | |
| 25 | 0 | kid1 | 24 | | | | | | | | | | | 0000-00-00 | | | | 0 | | | |
Which I need to be converted as below
| husband | wife | kid1 | kid2 | kid3 | kid4
sasas | | | | |
asd | | | | |
How can I modify my select query to group the records under
husband , wife , kid1 , kid2 , kid 3 and kid 4 ?
Your question is not exactly clear but it seems like you want to unpivot the existing columns and then pivot the values in the
user_typecolumn.If that is the case, then you will want to use a
UNION ALLto unpivot the data and then apply an aggregate function with aCASEexpression to pivot to get the final result:See SQL Fiddle with Demo. Your sample data does not have many values, but the result will be similar to this:
Note: I included additional columns to unpivot but if you only want the
fnameyou would only include those columns in the subqueryEdit #1, if you need to keep the order of the data based on the columns in the original table, then you can add a column to the
UNION ALLqueries with the sort order. You can then use that column in anORDER BY. So the query will be:See SQL Fiddle with Demo