将多行合并为一行

时间:2015-05-11 10:00:15

标签: mysql sql

我有一个非常复杂的查询来提取一些数据。结果集如下所示:

mon | tue  | wed | thu  | fri | sat  | sun |  dispatch | driver_id | name | phone
 x  |  x   |  x  |  x   |  x  | data |  x  |         1 |         2 | Bob  | 123
 x  | data |  x  |  x   |  x  |  x   |  x  |         1 |         2 | Bob  | 123
 x  |  x   |  x  | data |  x  |  x   |  x  |         1 |         2 | Bob  | 123

我想知道是否有人可以帮我将多个具有相同dispatch | driver_id | name | phone的列合并到 ONE ROW

因此,我最终会将此结果(所有data值替换为x值):

mon | tue  | wed | thu   | fri | sat   | sun |  dispatch | driver_id | name | phone
  x | data | x   | data  | x   | data  | x   |         1 |         2 | Bob  | 123
  • Data值不同且为TEXT,而x值始终表示为x
  • 将有各种dispatch | driver_id | name | phone组合

1 个答案:

答案 0 :(得分:2)

如果“x”值为NULL,则可以使用如下查询:

SELECT
  MAX(mon) AS mon,
  MAX(tue) AS tue,
  MAX(wed) AS wed,
  MAX(thu) AS thu,
  MAX(fri) AS fri,
  MAX(sat) AS sat,
  MAX(sun) AS sun,
  dispatch,
  driver_id,
  name,
  phone
FROM
  yourtable
GROUP BY
  dispatch,
  driver_it,
  name,
  phone

但是如果“x”值是确切的字符串“x”,那么你应该使用这样的东西:

MAX(CASE WHEN mon!='x' THEN mon END) as mon,
MAX(CASE WHEN tue!='x' THEN tue END) as tue,
...

这将起作用,除非两个或多个不同的行对同一列具有不同的值。