日期:2014-05-18 浏览次数:20375 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]([id] int,[ShopId] int,[ProductId] int,[Quantity] int) insert [test] select 1,1,1,1 union all select 2,1,2,2 union all select 3,1,3,1 union all select 4,2,2,1 union all select 5,3,1,3 union all select 6,3,3,1 declare @str varchar(8000) set @str='' select @str=@str+','+'[ShopId'+LTRIM([ShopId])+']=sum(case when ShopId='+ LTRIM(ShopId)+' then 1 else 0 end)' from [test] group by ShopId exec('select [ProductId]'+@str+' from test group by [ProductId]') /* ProductId ShopId1 ShopId2 ShopId3 1 1 0 1 2 1 1 0 3 1 0 1 */