Pregunta

Estoy intentando obtener todos los valores distintos en 2 tablas usando una unión.

La idea es obtener un recuento de todos los valores únicos en la columna columna A sin repeticiones para poder obtener una suma de todas las columnas que contienen una columna A única.

Esto es lo que probé (sql server express 2008)

select 
    count(Distinct ColumnA) 
from 
( 
    select Distinct ColumnA as ColumnA from tableX where x = y
    union
    select Distinct ColumnA as ColumnA from tableY where y=z
)
¿Fue útil?

Solución

SELECT COUNT(distinct tmp.ColumnA) FROM ( (SELECT ColumnA FROM TableX WHERE x=y) 
UNION (SELECT ColumnA FROM TableY WHERE y=z) ) as tmp

Los distincts adicionales en TABLEX y Tabley no son necesarios; Van a llegar despojados en la cláusula tmp.ColumnA. La declaración de una tabla temporal debe eliminar la ambigüedad que podría haber impedido su consulta a partir de la ejecución.

Otros consejos

SELECT COUNT(*)
FROM
(
SELECT DISTINCT ColumnA From TableX WHERE x = y
UNION
SELECT DISTINCT ColumnA From TableY WHERE y = z
) t

El uso de una "unión" no volverá duplicados. Si ha utilizado "UNION ALL" y luego duplicar los valores de columna de cada tabla sería retorno.

Para obtener valores distintos en la consulta de unión, puedes probar esto

Select distinct AUnion.Name,AUnion.Company from (SELECT Name,Company from table1 UNION SELECT Name,Company from table2)AUnion
SELECT DISTINCT Id, Name
FROM   TableA
UNION ALL
SELECT DISTINCT Id, Name
FROM   TableB
WHERE  TableB.Id NOT IN (SELECT Id FROM TableA)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top