日期:2014-05-17 浏览次数:20514 次
insert into 另一个表 select mcode,max(case when (id-1)%6=0 then custno end), max(case when (id-1)%6=1 then custno end), max(case when (id-1)%6=2 then custno end), max(case when (id-1)%6=3 then custno end), max(case when (id-1)%6=4 then custno end), max(case when (id-1)%6=5 then custno end) from 一个表 group by mcode,(id-1)%6 --这有点笔误
------解决方案--------------------
是不是这个意思:
CREATE TABLE t1 ( id INT, mcode VARCHAR(20), custno VARCHAR(10) ) INSERT INTO t1 SELECT 1, '1501050860000', 'J057' UNION ALL SELECT 2, '1501050860000', 'J1336' UNION ALL SELECT 3, '1501050860000', 'J1642' UNION ALL SELECT 4, '1501050860000', 'J1881' UNION ALL SELECT 5, '1501050860000', 'L0001' UNION ALL SELECT 6, '1501050860000', 'L0001' UNION ALL SELECT 7, '1501050860100', 'J057' UNION ALL SELECT 8, '1501050860200', 'J057' UNION ALL SELECT 9, '1501050860300', 'J1881' SELECT * FROM t1 DECLARE @sql VARCHAR(8000) SET @sql='select mcode' SELECT @sql=@sql+',max(case when id='+LTRIM(id)+' then custno else null end) as ['+LTRIM(id)+']' FROM (SELECT DISTINCT id FROM t1) AS a SET @sql=@sql+' from t1 group by mcode' PRINT @sql EXEC (@sql) mcode 1 2 3 4 5 6 7 8 9 1501050860000 J057 J1336 J1642 J1881 L0001 L0001 NULL NULL NULL 1501050860100 NULL NULL NULL NULL NULL NULL J057 NULL NULL 1501050860200 NULL NULL NULL NULL NULL NULL NULL J057 NULL 1501050860300 NULL NULL NULL NULL NULL NULL NULL NULL J1881
------解决方案--------------------
怎么看都像是做报表,怎么搞这么复杂,如果mcode有一万个,难道写一万个字段?