PrimuS
PrimuS

Reputation: 2683

MySQL DB with multiple numbers show as rows

I have a rather complicated question (for me at least)

I have the following table structure

| id | roomtype | roomno | feature
| 1  |    STDK  |   11   |  BT
| 2  |    STDK  |   11   |  AE
| 3  |    STDK  |   22   |  SMK
| 4  |    STDK  |   22   |  BT
| 5  |    STDT  |   33   |  NONSMK

and I want to have an output like this

Type: STDK - RoomNo: 11 - Features: BT, AE
Type: STDK - RoomNo: 22 - Features: SMK, BT
Type: STDT - RoomNo: 33 - Features: NONSMK

It's probably not that complicated but I can't get it...

Upvotes: 0

Views: 70

Answers (3)

Ariful Islam
Ariful Islam

Reputation: 7675

SELECT 
     roomtype AS Type, 
     roomno AS RoomNo, 
     GROUP_CONCAT(feature ORDER BY feature SEPARATOR ', ') AS Features
FROM 
    tableName
GROUP BY roomtype, roomno
ORDER BY roomno

Upvotes: 0

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

This shows the result you're looking for... But I don't like the idea of formatting the result in the query!

select
    concat("Type: ", roomtype,
    " - RoomNo: ", roomno,
    " - Features: ", group_concat(feature order by feature separator ', '))
    as result
from t1
group by roomtype, roomno

Here is a working example

Upvotes: 5

mu is too short
mu is too short

Reputation: 434665

You could use MySQL's group_concat:

select roomtype, roomno, group_concat(feature order by feature separator ', ')
from your_table
group by roomtype, roomno
order by roomno

Producing your fully formatted output from that is left as an exercise.

Upvotes: 3

Related Questions