2

The problem is:

select (..)
UNION 
select (..)

Result is:

Col1, Col2, Col3

 Val1    Text1  Data
 Val1    Text2  Data

The problem is that i need to save only 1 row of this two. Col2 value is not same at fact, but the same in business logic.

So, how to get result like this:

Col1, Col2,Col3
Val1  Text1 Data

OR

Col1, Col2, Col3
Val1  Text2 Data

Thank you!

4
  • 3
    Seems like what you want isn't a UNION but a JOIN. Maybe a FULL OUTER JOIN? UNION is doing exactly what it's supposed to be doing here; return each distinct row. Those rows are distinctly different, so UNION returns both. Commented Jul 21, 2021 at 8:34
  • Add your sample data and your full query. If you did use Union, there should not be 2 same rows. Commented Jul 21, 2021 at 8:57
  • 1
    Which columns decide whether it's a duplicate or not? Commented Jul 21, 2021 at 9:17
  • @Charlieface, Col1 and Col3 , not Col2. Commented Jul 21, 2021 at 13:40

2 Answers 2

2

You can place the UNION in a subquery and group again

SELECT
  Col1,
  MIN(Col2),
  Col3
FROM (
    SELECT Col1, Col2, Col3
    FROM table1 t1
    UNION ALL
    SELECT Col1, Col2, Col3
    FROM table2 t2
) t
GROUP BY
  Col1,
  Col2;

Note the use of UNION ALL rather than UNION, because you are grouping anyway it is not necessary to de-duplicate first.

Sign up to request clarification or add additional context in comments.

Comments

1

Hmmm . . . If you want one row per val, then one method is:

with t1 as ( < query 1 here > ),
     t2 as ( < query 2 here > )
select t1.*
from t1
union all
select t2.*
from t2
where not exists (select 1 from t1 where t1.val = t2.val);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.