Ver Mensaje Individual
  #5 (permalink)  
Antiguo 27/08/2015, 12:21
Avatar de richie_
richie_
 
Fecha de Ingreso: agosto-2015
Ubicación: Puebla
Mensajes: 6
Antigüedad: 8 años, 8 meses
Puntos: 0
Respuesta: columnas acumulables

la query seria esta :

Código SQL:
Ver original
  1. GO
  2. WITH fechas
  3.     AS
  4.     (
  5.         SELECT CAST ('20150601' AS DATE) AS Fecha
  6.         UNION ALL
  7.         SELECT DATEADD (D, 1, FECHA) AS FECHA
  8.         FROM FECHAS WHERE FECHA < CAST ('20150831' AS DATE)
  9.     )  
  10.     SELECT f.Fecha,
  11.      LAG((isnull(depositos.suma_dinero,0) - isnull(sales.total_de_montos,0)),1,0) OVER (ORDER BY f.Fecha) AS saldo_inicial,
  12.         ISNULL (depositos.suma_dinero,0) AS compras,
  13.         ISNULL(sales.total_de_montos, 0) AS total_ventas,
  14.         (LAG((isnull(depositos.suma_dinero,0) - isnull(sales.total_de_montos,0)),1,0) OVER (ORDER BY f.Fecha)+(isnull(depositos.suma_dinero,0) - isnull(sales.total_de_montos,0)) ) AS saldo_final
  15.  
  16. FROM fechas f
  17.     LEFT JOIN (
  18.                               SELECT SUM(t.monto) AS total_de_montos,
  19.                     COUNT(t.monto) AS numero_montos ,
  20.                     CONVERT(DATE,t.fecha_ingreso) AS fecha_ingreso             
  21.                 FROM ventas t
  22.                 WHERE (t.fecha_ingreso <=(SELECT DATEADD(ms,-3,DATEADD(dd,DATEDIFF(dd,0,GETDATE()),1))) AND t.fecha_ingreso >= (SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))) AND t.id_usuario = 29
  23.                 GROUP BY CONVERT(DATE,t.fecha_ingreso)     
  24.             ) sales
  25.     ON sales.fecha_ingreso = f.Fecha
  26.     LEFT JOIN (
  27.                 SELECT COUNT (dh.monto) AS dinero_depositado,
  28.                         SUM (dh.monto) AS suma_dinero,
  29.                         dh.fecha_deposito
  30.                 FROM usuario u
  31.                 INNER JOIN depositos_historicos dh
  32.                 ON u.usuario_id = dh.id_usuario
  33.                 WHERE u.usuario_id = 29 AND dh.id_estatus = 3
  34.                 GROUP BY dh.fecha_deposito
  35.             ) depositos
  36.     ON depositos.fecha_deposito = f.Fecha
  37.    
  38. ORDER BY f.Fecha ASC
  39. OPTION(maxrecursion 0)
  40.  
  41. GO

Última edición por richie_; 27/08/2015 a las 12:28