sql行列转换动态
发布时间: 2023-06-09 23:55:09
⑴ sql server 行转列
创建测试表
createtabletest
(_keyvarchar(10),
_valuevarchar(10),
idint)
insertintotestvalues('ceshi','测试值',10)
insertintotestvalues('ceshi','测试值',11)
insertintotestvalues('ceshi2','测试值2',11)
执行
declare@sqlvarchar(4000)
set@sql='selectid'
select@sql=@sql+',max(case_keywhen'''+[_key]+'''then[_value]end)as
['+_key+']'
from(selectdistinct_keyfromtest)asa
select@sql=@sql+'fromtestgroupbyid'
exec(@sql)
结果
额,我那个第三条数据id写错了,不过方法还是这个
⑵ sql 2000 结合两张表“动态”实现 行转列
select
bdate,
max(case when area='保养一区' then 1 else 0 end),
max(case when area='保养二区' then 1 else 0 end),
max(case when area='保养三区' then 1 else 0 end),
……
from tablename
group by bdate
热点内容