Skip to content

Instantly share code, notes, and snippets.

@jgomo3
Last active October 1, 2015 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgomo3/81fe21c5e1bd964b8063 to your computer and use it in GitHub Desktop.
Save jgomo3/81fe21c5e1bd964b8063 to your computer and use it in GitHub Desktop.
Comparación entre dos expresiones SQL, con y sin CTE
-- Sin CTE
select
nombre
, comp.cantidad_suma as cant_comp
, fact.cantidad_suma as cant_fact
from
productos as prod
, (select sum(cantidad) as cantidad_suma, producto from compras) as comp
, (select sum(cantidad) as cantidad_suma, producto from facturas) as fact
where
prod.producto = comp.producto
and fact.producto = prod.producto
;
-- Con CTE
with
cp as (select sum(cantidad) as cant_sum, producto from compras)
, ft as (select sum(cantidad) as cant_sum, producto from facturas)
, tot as (
select
cp.cant_sum as c_comp
, ft.cant_sum as c_fact
, ft.producto
from
cp
, ft
where
cp.producto = ft.producto
)
select
productos.nombre
, tot.c_comp
, tot.c_fact
from
productos
, tot
where
tot.producto = productos.product
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment