简体   繁体   中英

group or select distinct columns in mysql

I have a table like this

records            
columnA columnB columnC columnD
gary    2011    0       a
gary    2011    0       b
gary    2010    1       a
mary    2011    0       a
mary    2010    1       b
mary    2010    1       c

i want to parse the table and if i find multiple lines where columnA columnB columnC are common to display the values from these three columns once followed by values found on columnD from each records where those columns ABC where the same.

Something like this

print output           
gary    2011    0   a,b
gary    2010    1   a
mary    2011    0   a
mary    2010    1   b,c

I am using mysql, I tried with distinct but it duplicates the prints when found similar ABC columns. for example instead of displaying

gary   2011    0   a,b

once, it will disaply this line twice and so on three, four ... times, for each similar lines found...

Thank you, Mozley

You're looking for GROUP_CONCAT :

SELECT columnA, columnB, columnC,
     GROUP_CONCAT(DISTINCT columnD
               ORDER BY columnD ASC SEPARATOR ', ') AS columnD
     FROM records
     GROUP BY columnA, columnB, columnC

Result

| COLUMNA | COLUMNB | COLUMNC | COLUMND |
-----------------------------------------
|    gary |    2010 |       1 |       a |
|    gary |    2011 |       0 |    a, b |
|    mary |    2010 |       1 |    b, c |
|    mary |    2011 |       0 |       a |

See the demo

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