declare @a table(手机号 varchar(10),名称 varchar(10),数量 int,时间 datetime)
insert into @a
select '12345','销售量',20,'2013-01-01' union all
select '12345','销售量',55,'2013-01-02' union all
select '12345','销售量1',10,'2013-01-01'
select * into #t from @a
--上面是建表语句
declare @sql varchar(max)
select @sql=ISNULL(@sql,'')+',sum(case when 名称='+''''+名称+''''+' then 数量 else 0 end)as '+名称
from (select distinct 名称 from #t)a
set @sql='select 手机号'+@sql+',时间 from #t group by 手机号,时间'
exec(@sql)
drop table #t
drop table zhuan
create table zhuan(
No varchar(20),
Name varchar(20),
Zhi int,
Time datetime)
insert into zhuan
select '12345','销售量',55,'2013-04-24 10:30:00' union all
select '12345','销售量',20,'2013-04-24 10:43:20'
go
select No as 手机号,销售量,Time as 时间 from zhuan as b pivot(sum(Zhi) for Name in (销售量)) a