日期:2014-05-18 浏览次数:20505 次
select *,row_number() over (partition by id order by getdate()) as rnt into tp from tb declare @sql varchar(max) set @sql = 'select id' select @sql = @sql + ',max(case when rnt='+ltrim(rnt)+' then price else null end) [price'+ltrim(rnt)+']' from(select distinct rnt from tp) select @sql = @sql + ' from tp group by id' exec(@sql) drop table tp
------解决方案--------------------
IF OBJECT_id(N'FENG') IS NOT NULL DROP TABLE FENG GO CREATE TABLE FENG(id int,price VARCHAR(10)) INSERT FENG SELECT 1,2 UNION ALL SELECT 1,1 UNION ALL SELECT 2,0.1 UNION ALL SELECT 2,0.3 UNION ALL SELECT 2,0.4 GO IF OBJECT_ID('tempdb..#LSB') IS NOT NULL DROP TABLE #LSB GO SELECT ROW = ROW_NUMBER() OVER (PARTITION BY id ORDER BY (SELECT 0)) ,* INTO #LSB FROM FENG DECLARE @XK VARCHAR(50) ;WITH AA AS (SELECT DISTINCT ROW FROM #LSB ) SELECT @XK = ISNULL(@XK+',','')+QUOTENAME(ROW) FROM AA EXEC ('SELECT id,'+@XK+' FROM #LSB PIVOT(MAX(price) FOR ROW IN ('+@XK+')) PIV ORDER BY 1') /* id 1 2 3 1 2.0 1.0 NULL 2 0.1 0.3 0.4 */
------解决方案--------------------
如果非常多的话 把@XK 定义大一些 8000内
------解决方案--------------------