MySQL - GROUP multiple rows while retaining differences

喜夏-厌秋 提交于 2020-01-25 08:36:05

问题


I have a series of complicated MySQL select queries / joins that produce results similar to this:

|----|---------|----------|----------|---------------|---------------|
| id | company | city     | province | manager_email | staff_email   |
|----|---------|----------|----------|---------------|---------------|
| 1  | aaa     | toronto  | ON       | john@aaa.com  |               |
| 1  | aaa     | toronto  | ON       |               | smith@aaa.com |
| 2  | bbb     | sudbury  | ON       | john@bbb.com  |               |
| 3  | ccc     | hamilton | ON       | john@ccc.com  |               |
| 3  | ccc     | hamilton | ON       |               | smith@ccc.com |
|----|---------|----------|----------|---------------|---------------|
  • most "companies" have two rows, which are identical other than the emails
  • manager_email and staff_email will never appear in the same row
  • there are some cases where a "company" will only have one row

Is there a GROUP BY or a similar statement that I can use to group all of these duplicate rows, while retaining both emails? e.g.

|----|---------|----------|----------|---------------|---------------|
| id | company | city     | province | manager_email | staff_email   |
|----|---------|----------|----------|---------------|---------------|
| 1  | aaa     | toronto  | ON       | john@aaa.com  | smith@aaa.com |
| 2  | bbb     | sudbury  | ON       | john@bbb.com  |               |
| 3  | ccc     | hamilton | ON       | john@ccc.com  | smith@ccc.com |
|----|---------|----------|----------|---------------|---------------|

I'm willing to share more details if needed, but at this point I think it'll just add confusion.


回答1:


You can take advantage of the fact that most aggregate functions ignore null:

select 
    id, 
    company, 
    city, 
    province, 
    max(manager_email) manager_email, 
    max(staff_email) staff_email
from mytable
group by id, company, city, province


来源:https://stackoverflow.com/questions/58957478/mysql-group-multiple-rows-while-retaining-differences

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!