简体   繁体   中英

How to use Group By, but keep all other values in the column (in mysqli)

Is it possible to use Group By, yet keep all of the other associated values from the columns ?

month | date     | location
---------------------------
april  | 4/11/18 | US
april  | 4/16/18 | US
may    | 5/14/18 | Canada
june   | 6/05/18 | Canada
june   | 6/30/18 | US 

Basically, I want to show distinct values for the month, but match the date underneath the respective month, and keep the other values.

april: 4/11/18 (US), 4/16/18 (US)
may: 5/14/18 (Canada)
june: 6/05/18 (Canada), 6/30/18 (US)

Here is the code I used:

$query = ("SELECT * FROM events GROUP BY month");

This is just showing the distinct months.

Any help would be greatly appreciated.

Use GROUP_CONCAT

SQL DEMO

 SELECT month,
        GROUP_CONCAT( date, '(', location, ')' ) as data
 FROM YourTable
 GROUP BY month

OUTPUT

| month |                                                data |
|-------|-----------------------------------------------------|
| april |     2018-04-11 00:00:00(US),2018-04-16 00:00:00(US) |
|  june | 2018-06-05 00:00:00(Canada),2018-06-30 00:00:00(US) |
|   may |                         2018-05-14 00:00:00(Canada) |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM