从一张表中将多行选择为一行

时间:2019-08-06 12:29:29

标签: mysql sql

我有一张表格,其中包含多行相关数据,我需要将其作为一行进行查询。

string_value | def_id | location | model | asset_num |  exp_date  |
-------------+--------+----------+-------+-----------+------------+
  null       |  16    |    A     | CR35  |     1     | 2015-02-01 |
  SWIT: C    |  25    |    A     | CR35  |     1     |    null    |
  null       |  16    |    B     | CR85  |     2     | 2015-07-28 |
  SWIT: D    |  25    |    B     | CR85  |     2     |    null    |

我最终希望得到的查询可以给我结果:

string_value | location | model | asset_num |  exp_date  |
-------------+----------+-------+-----------+------------+
  SWIT: C    |    A     | CR35  |     1     | 2015-02-01 |
  SWIT: D    |    B     | CR85  |     2     | 2015-07-28 |

3 个答案:

答案 0 :(得分:1)

您可以尝试以下操作-使用汇总和分组依据

select location, model, asset_num,max(string_value),max(exp_date) 
from tablename
group by location, model, asset_num

答案 1 :(得分:1)

将聚合函数MAX()GROUP BY结合使用可返回预期结果:

SELECT MAX(string_value) AS string_value ,
       location,
       MAX(model) AS model,
       MAX(asset_num) AS asset_num,
       MAX(exp_date) AS exp_date  
FROM TableName
GROUP BY location

答案 2 :(得分:0)

我猜测三元组,模型,asset_num定义了结果集中的行。如果是这样,请使用聚合:

select location, model, asset_num,
       max(string_value) as string_value,
       max(exp_date) as exp_date
from t
group by location, model, asset_num;