WHY, why, why? Do I get an error:
"Msg 325, Level 15, State 1, Line 17 Incorrect syntax near 'PIVOT'. You may need to set the compatibility level of the current database to a higher value to enable this feature. See help for the stored procedure sp_dbcmptlevel." For this query?
WITH Offnet7 AS (
SELECT disposition.dispositiondesc, interaction.dispositionid, DATEPART(wk,interaction.ibegintime) as iWeek
FROM interaction INNER JOIN
disposition ON interaction.reasonid = disposition.dispositionid
WHERE interaction.dispositionid = 10 and (reasonid = 20365 or reasonid = 20366 or reasonid = 11168) and
interaction.ibegintime >= '2013-1-1' and
interaction.ibegintime < '2014-1-1'
)
SELECT iWeek, dispositiondesc, count(iWeek) as 'OffnetCounts'
FROM Offnet7
Group by dispositiondesc, iWeek
PIVOT
(
OffnetCounts
for iWeek in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15])
) AS counts
EDIT: Tried to make a SQL Fiddle, and it choked when I went to "Build Schema." (SQL Noob) I pulled the types from SQL management studio's object explorer and copied some example data. But this is what I attempted:
CREATE TABLE interaction
([reasonid] int, [dispositionid] int, [ibegintime] datetime)
;
INSERT INTO interaction
([reasonid], [dispositionid], [ibegintime])
VALUES
(20366, 10, '2012-01-31 23:59:48.000'),
(20366, 10, '2012-02-07 14:03:01.000'),
(20366, 10, '2012-02-07 14:06:48.000'),
(20366, 10, '2012-02-13 21:44:10.000'),
(20366, 10, '2012-02-27 21:36:33.000')
;
CREATE TABLE disposition
([dispositionid] int, [predefined] int, [dispositiondesc] varchar(64), [displayvalue] varchar(254))
;
INSERT INTO disposition
([dispositionid], [predefined], [dispositiondesc], [displayvalue])
VALUES
(10, 1, 'TRANSFERRED OFFNET', 'TRANSFERRED OFFNET'),
(11168, 0, 'TAKEDA PASSWORD', 'TAKEDA PASSWORD'),
(15433, 0, 'Voice Mail - TAKEDAEMEA', 'Voice Mail - TAKEDAEMEA'),
(20365, 0, 'TAKEDA iPAD, iPhone or BlackBerry', 'TAKEDA iPAD, iPhone or BlackBerry'),
(20366, 0, 'TAKEDA Concur', 'TAKEDA Concur')
;
Conclusion: Thanks for all the help Bluefeet!
For anyone interested in this, his first answer WOULD HAVE worked if the SQL compatibility level was set correctly by my DBA. After trying his first answer I got a:
"Msg 102, Level 15, State 1, Line 19 Incorrect syntax near '('."
Because the DBA doesn't have the SQL Server configured with a compatibility level that supports the PIVOT statement.