简体   繁体   中英

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:

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. 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;

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