Может быть что-то вроде этого:
Данные испытаний
CREATE TABLE Table1
(
ID INT,
Date DATETIME,
SiteUser INT,
WebSiteID INT,
WebSiteViews INT
)
INSERT INTO Table1
VALUES
(1,'2011-10-06 00:00:00:000',36,1,197),
(2,'2011-10-06 00:00:00:000',37,1,70),
(3,'2011-10-06 00:00:00:000',36,1,111),
(4,'2011-10-06 00:00:00:000',32,1,24),
(5,'2012-02-26 00:00:00:000',31,1,37),
(6,'2012-02-26 00:00:00:000',36,1,92),
(7,'2012-02-26 00:00:00:000',34,1,50),
(8,'2012-02-26 00:00:00:000',18,1,43),
(9,'2012-02-26 00:00:00:000',89,1,12),
(10,'2012-02-15 00:00:00:000',45,2,45),
(11,'2012-02-15 00:00:00:000',78,2,54),
(12,'2012-03-24 00:00:00:000',36,2,45),
(13,'2012-03-24 00:00:00:000',36,2,197),
(14,'2012-03-24 00:00:00:000',45,2,300),
(15,'2012-03-24 00:00:00:000',3,2,78),
(16,'2012-03-24 00:00:00:000',2,2,45),
(17,'2012-03-24 00:00:00:000',1,2,100),
(18,'2012-03-24 00:00:00:000',4,2,1)
Уникальные имена столбцов
DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY Table1.WebSiteID ORDER BY Table1.WebSiteID) AS RowNbr,
CAST(Table1.WebSiteID AS VARCHAR(100)) AS WebSiteID
FROM
Table1
)
SELECT @cols = COALESCE(@cols + ','+QUOTENAME('WebSiteID'+WebSiteID+'_Views'),
QUOTENAME('WebSiteID'+WebSiteID+'_Views'))
FROM
CTE
WHERE
CTE.RowNbr=1
Динамический пивот
DECLARE @SiteUser INT=36
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
convert(varchar(6), Date, 103)+RIGHT(CAST(YEAR(Date) AS VARCHAR(4)),2) AS Date,
Table1.WebSiteViews,
''WebSiteID''+CAST(WebSiteID AS VARCHAR(100))+''_Views'' AS WebSiteID
FROM
Table1
WHERE
Table1.SiteUser='+CAST(@SiteUser AS VARCHAR(100))+'
) AS p
PIVOT
(
SUM(WebSiteViews)
FOR WebSiteID IN ('+@cols+')
)AS pvt'
EXECUTE(@query)
В моем случае я опущу временную таблицу:
DROP TABLE Table1