日期:2014-05-17 浏览次数:20444 次
CREATE TABLE test (车型 VARCHAR(10), 年份 VARCHAR(10),月份 VARCHAR(10),数量 INT ) INSERT INTO test SELECT 'suv', '2003', '6月', 0 UNION ALL SELECT 'suv', '2003', '7月', 1 UNION ALL SELECT 'suv', '2003', '8月', 0 UNION ALL SELECT 'suv', '2003', '9月', 3 UNION ALL SELECT 'suv', '2003', '10月', 0 UNION ALL SELECT 'suv', '2003', '11月', 1 UNION ALL SELECT 'suv', '2003', '12月', 2 UNION ALL SELECT 'ft', '2003', '6月', 1 UNION ALL SELECT 'ft', '2003', '7月', 0 UNION ALL SELECT 'ft', '2003', '8月', 0 UNION ALL SELECT 'ft', '2003', '9月', 1 UNION ALL SELECT 'ft', '2003', '10月', 2 UNION ALL SELECT 'ft', '2003', '11月', 3 UNION ALL SELECT 'ft', '2003', '12月', 0 UNION ALL SELECT 'asd', '2004','1月', 2 UNION ALL SELECT 'asd', '2004', '2月', 1 UNION ALL SELECT 'asd', '2004', '3月', 0 SELECT 车型,SUBSTRING(年份+CASE WHEN LEN(SUBSTRING(月份,1,CHARINDEX('月',月份,1)))=2 THEN '0'+月份 ELSE 月份 END, 1,LEN(年份+CASE WHEN LEN(SUBSTRING(月份,1,CHARINDEX('月',月份,1)))=2 THEN '0'+月份 ELSE 月份 END)-1) 月份,数量 INTO #t FROM test declare @s nvarchar(4000) set @s='' Select @s=@s+','+quotename(SUBSTRING(月份,5,2))+'=max(case when [月份]='+quotename(月份,'''')+' then [数量] else 0 end)' from #t WHERE 月份 BETWEEN '200308' AND '200402' group BY 月份 exec('select [车型]'+@s+' from #t group by [车型]') /* 车型 08 09 10 11 12 01 02 ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- asd 0 0 0 0 0 2 1 ft 0 1 2 3 0 0 0 suv 0 3 0 1 2 0 0 (3 行受影响) */