简体   繁体   English

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

[英]Select multiple rows into one row from one table

I have a table with related data across multiple rows that I need to query as one row. 我有一张表,其中包含跨多行的相关数据,我需要将其查询为一行。

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    |

What I am looking to end up with is a query that gives me results: 我希望最终得到的查询可以给我结果:

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

You can Try below - using aggregation and group by 您可以在下面尝试-使用汇总和分组依据

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

Using aggregate function MAX() with GROUP BY return your expected result: 将聚合函数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

I am guessing that the triple location, model, asset_num defines the row in the result set. 我猜三重位置,模型,asset_num定义了结果集中的行。 If so, use aggregation: 如果是这样,请使用聚合:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MySQL - select 一张表的多行到一个结果行 - MySQL - select multiple rows from one table into one result row SQL从表1中选择一行加入表2中的多行 - SQL select one row from table 1 joining on multiple rows in table 2 从A表中的一行中多次选择,并将结果作为B表中的多行插入,并在一个查询中重复 - Multiple select from one row from A table and insert result as multiple rows in B table and repeat in one query 从一个表中选择一行,从另一表中选择多个行 - Select one row from one table and multiple rows from other table MySQL select 来自一个表的行,第二个表中有多行,并在所选行中获取多行数组 - MySQL select row from one table with multiple rows in a second table and get array of multi row in selected row 将表格中的一行与多行联接 - Join one row from a table with multiple rows 如何从一个表中选择单行和从另一个表中选择多行? - how to select single row from one table and multiple rows from another table toghether? 根据一个字段从多行中选择一行 - Select one row from multiple rows based on one field 从一个表中选择行,其中另一表中的多行已确定值 - Select row from one table where multiple rows in another table have determined values MySQL从一行中的其他表中选择具有多列的多行 - MySQL select multiple rows with multiple columns from other table in one row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM