简体   繁体   English

SQL获取基于列的单行中的合并行

[英]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 我正在寻找将以以下格式给出结果的SQL

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

In this SQL, I am checking for col = 'c?' 在此SQL中,我正在检查col ='c?' and printing out the corresponding Val. 并打印出相应的Val。 But the reason for group by is to avoid all NULL values in case the condition doesn't match. 但是分组依据的原因是要避免所有NULL值,以防条件不匹配。 By grouping on obj all the NULL values will be avoided and produce the desired result. 通过在obj上分组,将避免所有NULL值并产生所需的结果。

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 首先,您需要从表中选择所有唯一ID

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. 在这种情况下,我的方法仍然有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM