SQL 代码如下:
--下面创建一个临时表 #tb
create table #tb(db_element varchar(10),att_name varchar(10),att_value int)
--向临时表中插入测试数据
insert into #tb
select '张三','a',74 union all
select '张三','b',83 union all
select '张三','c',93 union all
select '李四','a',74 union all
select '李四','b',84 union all
select '李四','c',94
--下面是拼接SQL语句
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+','+att_name from #tb group by att_name
set @sql=stuff(@sql,1,1,'')
set @sql='select * from #tb pivot (max(att_value) for att_name in ('+@sql+')) a'
--执行拼接SQL 语句
exec(@sql)
--删除临时表
drop table #tb
--输出结果:
de_element a b c
李四 74 84 94
张三 74 83 93
2. 统计 SQL 关键字 group by
SQL 如下:
select a ,sum(b) as b,sum(c) as from table
group by a
select [time],sum(case when vs='胜' then 1 else 0 end) as 胜,
sum(case when vs='负' then 1 else 0 end) as 负
from tvs group by [time]
用as做别名 比如 select Time as 时间 from TB 得到的列名就是”时间“代替"Time"显示了 试试吧