简体   繁体   中英

Merging similar SQL rows

I want to merge rows base of some IF condition in SQL. 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.

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.

//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). That's why distinct and simply agrregate doesn't work

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 :

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

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

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