Foros del Web » Programación para mayores de 30 ;) » Bases de Datos General » SQL Server »

Datos inconsistente al colocar union

Estas en el tema de Datos inconsistente al colocar union en el foro de SQL Server en Foros del Web. Hola amigos del foro necesito una ayuda .. que tengo una union y al ejecutar el query por separado los resultados que obtengo son los ...
  #1 (permalink)  
Antiguo 24/02/2012, 09:21
 
Fecha de Ingreso: enero-2011
Mensajes: 58
Antigüedad: 13 años, 3 meses
Puntos: 0
Datos inconsistente al colocar union

Hola amigos del foro necesito una ayuda .. que tengo una union y al ejecutar el query por separado los resultados que obtengo son los deseados. pero con simplemenmte al colocar union en mi query los resultados son diferentes .. Espero alguien me pueda ayudar. Gracias. Aqui esta el query.

select (select top 1 (case MONTH(CONVERT(VARCHAR,cff.DOCDATE))

WHEN '01' THEN 'ENE'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'ABR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AGO'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DIC'
end) as MES from [SOP30200] cff where cff.SOPNUMBE = caf.SOPNUMBE) AS MES,

(select top 1 (case
WHEN RTRIM(caff.SALSTERR) between '10000' and '19999' THEN 'LA GRAN CARACAS'
WHEN RTRIM(caff.SALSTERR) between '20000' and '29999' THEN 'ZULIA-FALCON'
WHEN RTRIM(caff.SALSTERR) between '30000' and '39999' THEN 'CENTRO'
WHEN RTRIM(caff.SALSTERR) between '40000' and '49999' THEN 'LOS ANDES'
WHEN RTRIM(caff.SALSTERR) between '50000' and '59999' THEN 'LARA - LOS LLANOS'
WHEN RTRIM(caff.SALSTERR) between '60000' and '69999' THEN 'ORIENTE'
WHEN RTRIM(caff.SALSTERR) = '70000' THEN 'OFICINA'
end) as ZONA FRom [SOP30200] caff where caff.SOPNUMBE = caf.SOPNUMBE) as ZONA ,


cast(isnull(((select top 1 sum(quantity) FROM [SOP30300] d
inner join [SOP30200] fIn on d.SOPNUMBE = fIn.SOPNUMBE
where fIn.VOIDSTTS<>1
and fIn.SOPNUMBE = caf.SOPNUMBE
and fIn.SOPTYPE='3'
and fIn.SLPRSNID <> 'PROMOCIONES'
and fIn.SALSTERR between '10000' and '70000'
and fIn.DOCDATE between '01/01/2011' and '31/12/2011'
and d.[cmpntseq] not in ('16384','32768'))),0) -

isnull(((select top 1 sum(quantity) FROM [SOP30300] d
inner join [SOP30200] fIn on d.SOPNUMBE = fIn.SOPNUMBE
where fIn.VOIDSTTS<>1
and fIn.SOPNUMBE = caf.SOPNUMBE
and fIn.SOPTYPE='4'
and fIn.SALSTERR between '10000' and '70000'
and fIn.SLPRSNID <> 'PROMOCIONES'
and fIn.DOCDATE between '01/01/2011' and '31/12/2011'
and d.[cmpntseq] not in ('16384','32768'))),0) as int) unidades_total

from SOP30200 caf
inner join SOP30300 de on caf.SOPNUMBE = de.SOPNUMBE

where
caf.VOIDSTTS<>'1'
and de.[cmpntseq] not in ('16384','32768')
and caf.SLPRSNID <>'PROMOCIONES'
and (caf.SOPTYPE = '3' or caf.SOPTYPE = '4')
and( caf.SALSTERR between '10000' and '79999')
and (caf.DOCDATE between '01/01/2011' and '31/12/2011')

group by caf.SOPNUMBE

union

select (select top 1 (case MONTH(CONVERT(VARCHAR,cff.DOCDATE))

WHEN '01' THEN 'ENE'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'ABR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AGO'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DIC'
end) as MES from [SOP30200] cff where cff.SOPNUMBE = caf.SOPNUMBE) AS MES,

(select top 1 (case
WHEN RTRIM(caff.SALSTERR) between '10000' and '19999' THEN 'LA GRAN CARACAS'
WHEN RTRIM(caff.SALSTERR) between '20000' and '29999' THEN 'ZULIA-FALCON'
WHEN RTRIM(caff.SALSTERR) between '30000' and '39999' THEN 'CENTRO'
WHEN RTRIM(caff.SALSTERR) between '40000' and '49999' THEN 'LOS ANDES'
WHEN RTRIM(caff.SALSTERR) between '50000' and '59999' THEN 'LARA - LOS LLANOS'
WHEN RTRIM(caff.SALSTERR) between '60000' and '69999' THEN 'ORIENTE'
WHEN RTRIM(caff.SALSTERR) = '70000' THEN 'OFICINA'
end) as ZONA FRom [SOP30200] caff where caff.SOPNUMBE = caf.SOPNUMBE) as ZONA ,


cast(isnull(((select top 1 sum(quantity) FROM [SOP30300] d
inner join [SOP30200] fIn on d.SOPNUMBE = fIn.SOPNUMBE
where fIn.VOIDSTTS<>1
and fIn.SOPNUMBE = caf.SOPNUMBE
and fIn.SOPTYPE='3'
and fIn.SLPRSNID = 'PROMOCIONES'
and fIn.SALSTERR between '70000' and '70000'
and fIn.DOCDATE between '01/01/2011' and '31/12/2011'
and d.[cmpntseq] not in ('16384','32768'))),0) -

isnull(((select top 1 sum(quantity) FROM [SOP30300] d
inner join [SOP30200] fIn on d.SOPNUMBE = fIn.SOPNUMBE
where fIn.VOIDSTTS<>1
and fIn.SOPNUMBE = caf.SOPNUMBE
and fIn.SOPTYPE='4'
and fIn.SALSTERR between '70000' and '70000'
and fIn.SLPRSNID = 'PROMOCIONES'
and fIn.DOCDATE between '01/01/2011' and '31/12/2011'
and d.[cmpntseq] not in ('16384','32768'))),0) as int) unidades_total

from SOP30200 caf
inner join SOP30300 de on caf.SOPNUMBE = de.SOPNUMBE

where
caf.VOIDSTTS<>'1'
and de.[cmpntseq] not in ('16384','32768')
and caf.SLPRSNID = 'PROMOCIONES'
and (caf.SOPTYPE = '3' or caf.SOPTYPE = '4')
and( caf.SALSTERR between '70000' and '70000')
and (caf.DOCDATE between '01/01/2011' and '31/12/2011')

group by caf.SOPNUMBE
  #2 (permalink)  
Antiguo 24/02/2012, 10:42
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Datos inconsistente al colocar union

Muy bonito el query, pero cual es el error que te manda?? porque asi a buenas y primeras no se ve donde este el error :S
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #3 (permalink)  
Antiguo 24/02/2012, 12:42
 
Fecha de Ingreso: enero-2011
Mensajes: 58
Antigüedad: 13 años, 3 meses
Puntos: 0
Respuesta: Datos inconsistente al colocar union

hermano no me arroja ningun erro el query corre bien completo .. la diferencia esta en q cuando lo corro completo me da un resultado q no es .. pero corriendolo por separado y sumando los resultados si me dan concretos los resultados
  #4 (permalink)  
Antiguo 24/02/2012, 12:59
 
Fecha de Ingreso: enero-2011
Mensajes: 58
Antigüedad: 13 años, 3 meses
Puntos: 0
De acuerdo Respuesta: Datos inconsistente al colocar union

hermano no me arroja ningun error el query corre bien completo .. la diferencia esta en q cuando lo corro completo me da un resultado q no es .. pero corriendolo por separado y sumando los resultados si me dan concretos los resultados
  #5 (permalink)  
Antiguo 24/02/2012, 13:13
Colaborador
 
Fecha de Ingreso: enero-2007
Ubicación: México
Mensajes: 2.097
Antigüedad: 17 años, 4 meses
Puntos: 447
Respuesta: Datos inconsistente al colocar union

Hola m1di:

Hay que tener algunas consideraciones al momento de utilizar UNION:

Primero, si existen elementos que puedan aparecer en ambas partes de la unión y QUIERES QUE SE REPITAN debes utilizar UNION ALL, ya que de lo contrario la unión simple ELIMINA LOS REGISTROS DUPLICADOS.

Segundo, no es lo mismo realizar agrupaciones sobre las subconsultas QUE SOBRE EL RESULTADO DE LA UNIÓN.

supongamos que tienes dos tablas con la siguiente información:

Código:
TABLA1
id          descripcion cantidad
----------- ----------- -----------
1           uno         10
2           dos         20
3           tres        30
1           uno         40
2           dos         50

TABLA2
id          descripcion cantidad
----------- ----------- -----------
1           uno         10
4           cuatro      20
5           cinco       30
4           cuatro      40
5           cinco       50
Observa cómo se comporta la unión dependiendo de cómo manejas el parámetro ALL y la agrupación:

Código SQL:
Ver original
  1. SELECT id, descripcion, SUM(cantidad) FROM @tabla1 GROUP BY id, descripcion
  2. UNION ALL
  3. SELECT id, descripcion, SUM(cantidad)  FROM @tabla2 GROUP BY id, descripcion ORDER BY id
  4. /*
  5. id          descripcion
  6. ----------- ----------- -----------
  7. 1           uno         10
  8. 1           uno         50
  9. 2           dos         70
  10. 3           tres        30
  11. 4           cuatro      60
  12. 5           cinco       80
  13. */
  14.  
  15. SELECT id, descripcion, SUM(cantidad) FROM
  16. (
  17. SELECT id, descripcion, cantidad FROM @tabla1
  18. UNION
  19. SELECT id, descripcion, cantidad FROM @tabla2
  20. ) T
  21. GROUP BY id, descripcion ORDER BY id
  22.  
  23. /*
  24. id          descripcion
  25. ----------- ----------- -----------
  26. 1           uno         50
  27. 2           dos         70
  28. 3           tres        30
  29. 4           cuatro      60
  30. 5           cinco       80
  31. */
  32.  
  33. SELECT id, descripcion, SUM(cantidad) FROM
  34. (
  35. SELECT id, descripcion, cantidad FROM @tabla1
  36. UNION ALL
  37. SELECT id, descripcion, cantidad FROM @tabla2
  38. ) T
  39. GROUP BY id, descripcion ORDER BY id
  40. /*
  41. id          descripcion
  42. ----------- ----------- -----------
  43. 1           uno         60
  44. 2           dos         70
  45. 3           tres        30
  46. 4           cuatro      60
  47. 5           cinco       80
  48. */

En el primer caso NO AGRUPA LAS DESCRIPCIONES DE LA UNIÓN RESULTANTE, solo las de las subconsultas.

En el segundo caso, el registro

Código:
id          descripcion cantidad
----------- ----------- -----------
1           uno         10
aparece en ambas tablas, por lo tanto SÓLO SE CONTABILIZA UNA VEZ, es decir se eliminan los duplicados al no utilizar el parámetro ALL

En el tercer caso SI SE REALIZA LA AGRUPACIÓN SOBRE EL RESULTADO DE LA UNIÓN Y TAMBIÉN SE CONTABILIZAN LOS REGISTROS DUPLICADOS.

Saludos
Leo.
  #6 (permalink)  
Antiguo 24/02/2012, 14:22
 
Fecha de Ingreso: enero-2011
Mensajes: 58
Antigüedad: 13 años, 3 meses
Puntos: 0
De acuerdo Respuesta: Datos inconsistente al colocar union

Hermano muchas gracias por su respuesta ya solvente el problema .. Con la union all.. Gracias de verdad.

Etiquetas: select, union
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 08:05.