简体   繁体   English

合并类似的SQL行

[英]Merging similar SQL rows

I want to merge rows base of some IF condition in SQL. 我想在SQL中合并一些IF条件的行基。 My database looks like this 我的数据库看起来像这样

| com_id | bom_id |fil_title
=====================
| 6067   | 6070   |NULL
| 6067   | 6070   |07
| 6067   | 6071   |NULL
| 6067   | 6071   |07
| 6067   | 6069   |NULL

What I want to achieve is 我想要实现的是

| com_id | bom_id |fil_title
=====================
| 6067   | 6070   |07
| 6067   | 6071   |07
| 6067   | 6069   |NULL

So every time if i had two rows with same bom_id i want to merge them in one, but if I had one just leave it. 因此,每次如果我有两行具有相同的bom_id我想将它们合并为一个,但如果我有一个只是离开它。

It's just a sample - my full query is bigger, but problem is just there. 这只是一个例子 - 我的完整查询更大,但问题就在那里。 I know that SQL has some IF but I don't know really how to use it here. 我知道SQL有一些IF,但我不知道如何在这里使用它。

//EDIT What I didn't mention precisely I have more fields with some random values. //编辑我没有提到的确切地说我有更多带有一些随机值的字段。 I want to pick this values only from row which is not null. 我想只从非空的行中选择这个值。 (but only if we had 2 rows). (但只有我们有2行)。 That's why distinct and simply agrregate doesn't work 这就是为什么明显和简单的agrregate不起作用的原因

Just do aggregation : 只做聚合

select com_id, bom_id, max(fil_title)
from table t
group by com_id, bom_id;

If that example result is from other query then use subquery instead : 如果该示例结果来自其他查询,则使用subquery

select com_id, bom_id, max(fil_title)
from ( <query here>
     ) t
group by com_id, bom_id;

Or you can use distinct to do so 或者您可以使用distinct来这样做

select com_id , bom_id , max(fil_title)
from table t
group by com_id , bom_id

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

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