Unir 2 querys

29/09/2007 - 06:47 por Pablo_Hack | Informe spam
Amigos he buscado por todo internet, he agotado todas las instacias q
me llevan a lo mismo.
El problema es el Siguiente. lo hare en un ejemplo simple.
Query1:
select ID ,count(*) as total1 from tabla1 group by ID
ID total1
1 5
2 15
3 15
5 3

Query2:
select ID ,count(*) as total2 from tabla1 where sesion>150 group by
ID
ID total2
1 9
5 16


Quiero q salga asi:
ID total1 total2
1 5 9
2 15
3 15
5 3 16


La pregunta es la siguiente. como lo hago en realidad es unir las dos
consultas en una, se puede? porfavor confio en ustedes.
 

Leer las respuestas

#1 Carlos M. Calvelo
29/09/2007 - 11:36 | Informe spam
On 29 sep, 06:47, Pablo_Hack wrote:
Amigos he buscado por todo internet, he agotado todas las instacias q
me llevan a lo mismo.
El problema es el Siguiente. lo hare en un ejemplo simple.
Query1:
select ID ,count(*) as total1 from tabla1 group by ID
ID total1
1 5
2 15
3 15
5 3

Query2:
select ID ,count(*) as total2 from tabla1 where sesion>150 group by
ID
ID total2
1 9
5 16

Quiero q salga asi:
ID total1 total2
1 5 9
2 15
3 15
5 3 16

La pregunta es la siguiente. como lo hago en realidad es unir las dos
consultas en una, se puede? porfavor confio en ustedes.



La respuesta ya está casi escrita :)
Los resultados de Query1 y Query2 "son" tablas;
haces un left join de query1 con query2 y ya está:

select t1.ID, t1.total1, t2.total2
(select ID ,count(*) as total1 from tabla1 group by ID) t1 --Query1
left join
(select ID ,count(*) as total2 from tabla1 where sesion>150 group by
ID) t2 -- query2
on t1.ID=t2.ID

Pero bueno... seguro que estás buscando esto:
select ID, count(*) as total1,
sum(case when sesion>150 then 1 else 0 end) as total2
from tabla1
group by ID

Saludos,
Carlos

Preguntas similares