Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   SQL (https://www.clubdelphi.com/foros/forumdisplay.php?f=6)
-   -   Restar 2 select (https://www.clubdelphi.com/foros/showthread.php?t=67501)

ingel 20-04-2010 15:41:27

Restar 2 select
 
Hola .. necesito restar 2 select y que el resultado sea un solo registro..
(en SQL 2000)

ej.

Select Sum(campo1) as Total from tabla1 -- > supongamos devuelve 9

select sum(campo2) as Total from tabla2 -- > sup. devuelve 4

Necesito que la instruccion devuelva un solo registro con el valor 5.

Deberia ser algo tan simple como poner un signo MENOS entre los select o algo asi ... pero probe con "-" , "MINUS" , "RESTAR" , ... "QUITAMELO O TE ASESINO".. pero nada ...

Sds y gracias por su tiempo...

TOPX 20-04-2010 15:53:59

Hola,

Sin haberlo probado y estando medio dormido, se me ocurre que puede intentar:
Código SQL [-]
select total1 - total2
from (
 select sum(campo1) as total1
 from tabla1
  union all
 select sum(campo2) as total2
 from tabla2
)

ingel 20-04-2010 16:19:05

Gracias por el madrugon ...
 
Hola Topx .. era buena la idea ... asi como esta escrita da error de sintaxis

Lo que hice fue crear una VISTA con la UNION ... peeero no logro que
el SELECT me devuelta UN REGISTRO ! ... me devuelve los DOS..
sigo en la lucha ...
gracias

Caro 20-04-2010 16:28:32

Hola ingel, con UNION no te va a tomar como dos campos diferentes sino la cantidad de registros que tengan ambos select en tu caso 2. A mi se me ocurre algo así:

Código SQL [-]
Select Sum(campo1) - (Select Sum(campo2) From tabla2) As Total
From tabla1

Saluditos

ingel 20-04-2010 16:46:08

gracias Caro .. .creo que eso va a funcionar
 
saluditos..

TOPX 20-04-2010 16:54:00

Vale, tienen razón. Yo por acá pude hacerlo así:

Código SQL [-]
select sum(total)
from (
 select sum(campo1) as total
 from tabla1
  union all
 select sum(campo2)*(-1) as total
 from tabla2
)

Y así también:

Código SQL [-]
select 
 (
  select sum(campo1) as total1
  from tabla1
 ) - (
  select sum(campo2) as total2
  from tabla2
 )

Caro 20-04-2010 17:35:02

Cita:

Empezado por TOPX (Mensaje 361216)
.............Yo por acá pude hacerlo así:

Código SQL [-]
select sum(total)
from (
select sum(campo1) as total
from tabla1
union all
select sum(campo2)*(-1) as total
from tabla2
)




Y así también:


Código SQL [-]
select
(
select sum(campo1) as total1
from tabla1
) - (
select sum(campo2) as total2
from tabla2
)



Hola TOPX, el primero si funciona ;), pero al segundo le falta el From, al no tener el From daría error.

Saluditos


La franja horaria es GMT +2. Ahora son las 22:13:27.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi