Saya telah memodifikasi SQL Fiddle yang diberikan dalam komentar yang akan memberi Anda hasil yang diinginkan, asalkan Anda sudah memiliki total harian:
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
Jika Anda ingin menjadikannya satu pernyataan, Anda perlu mengganti DailyTotals dengan subquery Anda yang memberi Anda total harian. Namun saya sarankan untuk membuat tampilan yang disebut DailyTotals dan menggunakannya.
EDIT:
Anda dapat menggunakan CTE untuk menghasilkan rentang tanggal Anda alih-alih tabel temp. Saya telah memodifikasi kueri lengkap Anda yang menurut Anda berfungsi untuk bergabung dengan CTE alih-alih @temp. Saya tidak punya cara untuk mengujinya. Jika ini tidak berhasil, buat SLQ Fiddle dengan skema Anda dan saya akan mencobanya lagi.
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