4

I cannot figure out how to merge 4 different columns from 2 different tables together into just one single column of all possible results, with duplicates removed. The actual names are different, but suppose I have the following two tables

Table1

  1. Field1
  2. Field2
  3. SomethingElse

Table2

  1. Field1
  2. Field2
  3. SomethingElse

Now in the end, I would like to merge all 4 of these fields together into one large field, and then use distinct on top of that to eliminate any duplicates, as there are many of them. The final result should be just one single column containing every possible value found in all 4 columns, without any duplicated.

When I was working with just one single table with two fields, I had it working fine:

select distinct(Field1) from Table1 where SomethingElse = SomeVal
union
(select distinct(Field2) from Table1 where SomethingElse = SomeVal)
order by 1

(of course I wished to have run distinct around the final result rather than each field)

Now I needed to add 2 more fields from another table. Nothing I have tried has even run, can't get the syntax right.

4

2 回答 2

7

这是一种方法:

select distinct val
from ((select field1 as val from table1 where somethingelse = someval) union all
      (select field2 from table1 where somethingelse = someval) union all
      (select field1 from table2 where somethingelse = someval) union all
      (select field2 from table2 where somethingelse = someval)
     ) t

我使用合并子查询union all,然后只distinct在外层执行一次。

因为我想知道的下一件事是这些值的使用位置,所以这里是查询:

select val, SUM(t1f1), SUM(t1f2), SUM(t2f1), SUM(t2f2)
from ((select field1 as val, 1 as t1f1, 0 as t1f2, 0 as t2f1, 0 as t2f2 from table1 where somethingelse = someval) union all
      (select field2, 0 as t1f1, 1 as t1f2, 0 as t2f1, 0 as t2f2 from table1 where somethingelse = someval) union all
      (select field1, 0 as t1f1, 0 as t1f2, 1 as t2f1, 0 as t2f2 from table2 where somethingelse = someval) union all
      (select field2, 0 as t1f1, 0 as t1f2, 0 as t2f1, 1 as t2f2 from table2 where somethingelse = someval)
     ) t
group by val
于 2012-12-26T18:52:51.903 回答
1
select distinct(Field1) from 
(
select Field1 [Field1] from Table1 where SomethingElse = SomeVal
union all
select Field2 [Field1] from Table1 where SomethingElse = SomeVal
) rawResults
order by 1

像这样的东西应该工作。只需将您的选择组合在一起并将其放在一个内联视图中,然后将您的独特和排序放在外面。我使用 union all 因为无论如何你都要在外面做一个不同的一次

于 2012-12-26T18:57:07.257 回答