sql >> Base de Datos >  >> RDS >> Sqlserver

combinar hoy y el total anterior a partir de hoy de esa misma columna da como resultado una consulta sql

Modifiqué el SQL Fiddle dado en el comentario que le dará el resultado deseado, siempre que ya tenga los totales diarios:

http://www.sqlfiddle.com/#!6/09168/2

DECLARE @startDate datetime
DECLARE @endDate datetime

SELECT @startDate = '2012-10-08'
SELECT @endDate = '2012-10-12'

SELECT
    DT1.ddate,
    DT1.phone,
    DT1.letter,
    DT1.email,
    DT1.web,
    SUM(DT2.phone) phoneTotal,
    SUM(DT2.letter) letterTotal,
    SUM(DT2.email) emailTotal,
    SUM(DT2.web) webTotal 
  FROM
    DailyTotals DT1
    LEFT JOIN DailyTotals DT2 ON DT1.ddate >= DT2.ddate AND DT2.ddate >= @startDate
  WHERE
    DT1.ddate <= @endDate
  GROUP BY
  DT1.ddate,
  DT1.phone,
  DT1.letter,
  DT1.email,
  DT1.web

Si desea convertirlo en una declaración, deberá reemplazar DailyTotals con su subconsulta que le brinda los totales diarios. Sin embargo, sugeriría crear una vista llamada DailyTotals y usarla.

EDITAR:

Puede usar un CTE para generar su rango de fechas en lugar de la tabla temporal. Modifiqué su consulta completa que dice que funciona para unirse con el CTE en lugar de @temp. Aunque no tengo forma de probarlo. Si esto no funciona, cree un SLQ Fiddle con su esquema y lo intentaré de nuevo.

WITH Dates AS
(
    SELECT CONVERT(date, MIN(ComplaintTime)) AS ddate,
    MAX(ComplaintTime) as EndDate
    FROM
      Complaints
    UNION ALL
    SELECT DATEADD(DAY, 1, ddate), EndDate
    FROM Dates
    WHERE DATEADD(DAY, 1, ddate) <= EndDate
    )

SELECT * FROM 

        (select ddate,ISNULL(L,0) AS Letter,
          ISNULL(P,0) AS Phone,
          ISNULL(E,0) AS Email,
          ISNULL(W,0) AS WEB 
          FROM 
          (
            select   ComplaintMedia_Abbri,
          ddate,COUNT(ComplaintMedia)  as c
            from    Complaint 
            INNER JOIN Dates
            ON convert(date,ComplaintDate)=ddate OPTION (MAXRECURSION 500)
            WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1     
            group by ComplaintMedia_Abbri,ddate
    ) p 

    pivot (SUM(c) FOR ComplaintMedia_Abbri IN (E,W,L,P)) AS pvt 

    ) AS [A]

    INNER JOIN 

    (
    select ddate,ISNULL(L,0) AS LetterTot,
      ISNULL(P,0) AS PhoneTot,
      ISNULL(E,0) AS EmailTot,
      ISNULL(W,0) AS WEBTot
      FROM 
      (

    select   ComplaintMedia_Abbri,ddate,
    COUNT(ComplaintMedia_Abbri)  as c
    from    Complaint 

    INNER JOIN Dates OPTION (MAXRECURSION 0)
    ON CONVERT(date,ComplaintDate) <= ddate OPTION (MAXRECURSION 0)

    WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1     
    group by ComplaintMedia_Abbri,ddate
    ) p 

   pivot (SUM(c) FOR ComplaintMedia_Abbri IN (E,W,L,P)) AS pvt



    ) AS [B]

   ON A.ddate=B.ddate

   order by A.ddate