简体   繁体   中英

SQL to get combine rows in single row based on a column

I have a table as follow:

+---+---+---+
|obj|col|Val|
+---+---+---+
|1  |c1 | v1|
+---+---+---+
|1  |c2 | v2|
+---+---+---+
|2  |c1 | v3|
+---+---+---+
|2  |c2 | v4|
+---+---+---+

And I am looking for SQL that will give the result in the following format

+---+---+---+
|obj|c1 |c2 |
+---+---+---+
|1  |v1 | v2|
+---+---+---+
|2  |v3 | v4|
+---+---+---+

In this SQL, I am checking for col = 'c?' and printing out the corresponding Val. But the reason for group by is to avoid all NULL values in case the condition doesn't match. By grouping on obj all the NULL values will be avoided and produce the desired result.

SELECT obj,
       MAX( CASE WHEN col = 'c1' THEN Val END ) AS c1,
       MAX( CASE WHEN col = 'c2' THEN Val END ) AS c2
  FROM Table
 GROUP BY obj;

First you need to select all the unique id from your table

select distinct id
from a_table_you_did_not_name

how you can use that to left join to your columns

select base.id, one.val as c1, two.val as c2
from (
  select distinct id
  from a_table_you_did_not_name
) base
left join a_table_you_did_not_name one on one.id = base.id and one.col = 'c1'
left join a_table_you_did_not_name two on two.id = base.id and two.col = 'c2'

note: your case is a relatively simple case of this kind of join -- I coded it like this because using my method can be extended to the more complicated cases and still work. There are some other ways for this particular requirement that might be simpler.

specifically the most common one is joining to multiple tables, not all in the same table. My method will still work in those cases.

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