Jump to content

Multiple Row -> One Row


mattbru

Recommended Posts

I need to combine multiple rows into one row for a query.  Given the table:

 

TIME  |  ID  |  STATUS

9          1        GOOD

9          2        BAD

9          3        GOOD

10        1        GOOD

10        2        GOOD

10        3        BAD

 

I would want:

 

TIME  |  ID 1  |  ID 2  |  ID 3 

9          GOOD    BAD    GOOD

10        GOOD    GOOD  BAD

 

Also, there may be a variable number of ID's per time (not just 3).

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/165798-multiple-row-one-row/
Share on other sites

Hi

 

Can't see a way to do that. It would bring back a variable number of columns.

 

You could use GROUP_CONCAT to put the fields into one:-

 

SELECT `TIME` GROUP_CONCAT(`STATUS` SEPARATOR ',')
FROM SomeTable
GROUP BY `TIME`

 

You could then explode the status field in php if you wanted.

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/165798-multiple-row-one-row/#findComment-874557
Share on other sites

Hi

 

Can't see a way to do that. It would bring back a variable number of columns.

 

You could use GROUP_CONCAT to put the fields into one:-

 

SELECT `TIME` GROUP_CONCAT(`STATUS` SEPARATOR ',')
FROM SomeTable
GROUP BY `TIME`

 

You could then explode the status field in php if you wanted.

 

All the best

 

Keith

 

 

Okay, thanks.  Suppose it was limited to a specific number, say 5 ID's per time?

Link to comment
https://forums.phpfreaks.com/topic/165798-multiple-row-one-row/#findComment-874561
Share on other sites

Hi

 

Possibly, but cannot see a way of doing it without it being either too complicated for something simple or too slow (or both).

 

Something like this might work:-

 

SELECT DISTINT `TIME`, b.STATUS, c.STATUS, d.STATUS, e.STATUS, f.STATUS
FROM SomeTable a
LEFT OUTER JOIN (SELECT STATUS FROM SomeTable z WHERE z.`TIME` = a.`Time LIMIT 0,1) b ON a.`TIME` = b.`TIME`
LEFT OUTER JOIN (SELECT STATUS FROM SomeTable y WHERE y.`TIME` = a.`Time LIMIT 1,1) c ON a.`TIME` = c.`TIME`
LEFT OUTER JOIN (SELECT STATUS FROM SomeTable x WHERE x.`TIME` = a.`Time LIMIT 2,1) d ON a.`TIME` = d.`TIME`
LEFT OUTER JOIN (SELECT STATUS FROM SomeTable w WHERE w.`TIME` = a.`Time LIMIT 3,1) e ON a.`TIME` = e.`TIME`
LEFT OUTER JOIN (SELECT STATUS FROM SomeTable v WHERE v.`TIME` = a.`Time LIMIT 4,1) f ON a.`TIME` = f.`TIME`

 

but not a nice idea (and not tested at all).

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/165798-multiple-row-one-row/#findComment-874568
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.