What I want to do is quite simple but I'm struggling. I'm hoping that someone can help.
I have this query that I've written.
DECLARE @LeadGenerator AS nvarchar(20) = 'Employee Name'
SELECT C.BaseDate AS BaseDate
,COUNT(P.OwnCreatedDate) AS CreatedLeads
,COUNT(P2.OwnCreatedDate) AS CreatedResearchedLeads
,COUNT(P3.AppointmentFeatureDate) AS AppointmentsMade
FROM dwCalendar C
LEFT JOIN dwTable P ON P.OwnCreatedDate = C.BaseDate AND P.OwnerStatus NOT IN ('Researched') AND P.LeadAssignee = @LeadGenerator
LEFT JOIN dwTable P2 ON P2.OwnCreatedDate = C.BaseDate AND P2.OwnerStatus IN ('Researched') AND P2.LeadAssignee = @LeadGenerator
LEFT JOIN dwTable P3 ON P3.AppointmentFeatureDate = C.BaseDate AND P3.LeadAssignee = @LeadGenerator
WHERE C.BaseDate BETWEEN DATEADD(DD, -8, GETDATE()) AND DATEADD(DD, -1, GETDATE())
GROUP BY C.BaseDate
It returns the data in this format:
Basedate | CreatedLeads | CreatedLeads | AppointmentsMade
2015-06-18 | 1 | 2 | 0
2015-06-19 | 2 | 1 | 2
2015-06-20 | 1 | 1 | 1
2015-06-21 | 1 | 2 | 3
2015-06-22 | 2 | 0 | 0
2015-06-23 | 3 | 2 | 2
2015-06-24 | 0 | 0 | 1
I want to pivot the data so that the Dates are across the top and then, CreatedLeads, CreatedLeadsResearched and a AppointmentsMade become the start of the rows and then the data.
So the data looks more like this:
2015-06-18 | 2015-06-19 | 2015-06-20 | 2015-06-21
CreatedLeads | Respective data in here
CreatedLeadsResearched |
AppointmentsMade |
If someone could please help that would be great as I am stuck?
Thanks in advance,
Thanks for the help, I've tried the script and this is the sql:
DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
DECLARE @LeadGenerator AS nvarchar(20) = 'Employee Name'
SELECT @cols = STUFF(( SELECT distinct ',' + QuoteName([BaseDate])
FROM dwCalendar FOR XML PATH('') ), 1, 1, '')
SET @sqlquery = 'SELECT * FROM
(
SELECT C.BaseDate AS BaseDate
,COUNT(P.OwnCreatedDate) AS CreatedLeads
,COUNT(P2.OwnCreatedDate) AS CreatedResearchedLeads
,COUNT(P3.AppointmentFeatureDate) AS AppointmentsMade
FROM dwCalendar C
LEFT JOIN dwOwnerTouchPoints P ON P.OwnCreatedDate = C.BaseDate AND P.OwnerStatus NOT IN (''Researched'') AND P.LeadAssignee = @LeadGenerator
LEFT JOIN dwTable P2 ON P2.OwnCreatedDate = C.BaseDate AND P2.OwnerStatus IN (''Researched'') AND P2.LeadAssignee = @LeadGenerator
LEFT JOIN dwTable P3 ON P3.AppointmentFeatureDate = C.BaseDate AND P3.LeadAssignee = @LeadGenerator
WHERE C.BaseDate BETWEEN DATEADD(DD, -8, GETDATE()) AND DATEADD(DD, -1, GETDATE())
GROUP BY C.BaseDate ) base
PIVOT (Sum(CreatedLeads) FOR [BaseDate]
IN (' + @cols + ')) AS finalpivot'
EXECUTE ( @sqlquery )
However when I try this I'm getting this error:
Msg 137, Level 15, State 2, Line 11
Must declare the scalar variable "@LeadGenerator".
Msg 105, Level 15, State 1, Line 19
Unclosed quotation mark after the character string 'Apr 28 20)) AS
finalpivot'.
Really sorry I just don't understand whats going on here.