日期:2014-05-17 浏览次数:20391 次
CREATE TABLE #TEST ( ID INT, SEGMENT CHAR (1), RESPONSES INT, CHECKED SMALLDATETIME )
INSERT INTO #TEST VALUES (1, 'A', 0, '2009-05-01') INSERT INTO #TEST VALUES (2, 'B', 1, '2009-05-01') INSERT INTO #TEST VALUES (3, 'C', 0, '2009-05-01') INSERT INTO #TEST VALUES (4, 'A', 0, '2009-05-02') INSERT INTO #TEST VALUES (5, 'B', 2, '2009-05-02') INSERT INTO #TEST VALUES (6, 'C', 1, '2009-05-02') INSERT INTO #TEST VALUES (7, 'A', 1, '2009-05-03') INSERT INTO #TEST VALUES (8, 'B', 0, '2009-05-03') INSERT INTO #TEST VALUES (9, 'C', 2, '2009-05-03')
DECLARE @s VARCHAR(MAX) SELECT @s=ISNULL(@s+',','')+QUOTENAME(SEGMENT) FROM #TEST GROUP BY SEGMENT EXEC('SELECT * FROM ( SELECT SEGMENT , RESPONSES , CHECKED FROM #TEST ) AS t PIVOT ( MAX(RESPONSES) FOR SEGMENT IN ('+@s+') ) AS piv') /* CHECKED A B C 2009-05-01 00:00:00 0 1 0 2009-05-02 00:00:00 0 2 1 2009-05-03 00:00:00 1 0 2 */