Jeg har ændret SQL Fiddle i kommentaren, som vil give dig det ønskede output, forudsat at du allerede har de daglige totaler:
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
Hvis du vil gøre det til én erklæring, skal du erstatte DailyTotals med din underforespørgsel, der giver dig de daglige totaler. Jeg vil dog foreslå, at du laver det til en visning kaldet DailyTotals og bruger det.
EDIT:
Du kan bruge en CTE til at generere dit datointerval i stedet for temp-tabellen. Jeg har ændret din fulde forespørgsel, som du siger virker til at slutte sig til CTE i stedet for @temp. Jeg har dog ingen mulighed for at teste det. Hvis dette ikke virker, skal du oprette en SLQ Fiddle med dit skema, så prøver jeg det igen.
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