如上图所示:9条数据其实只代表2种 db_element。 只不过这个2种db_element分别有几个属性而已,从上图中可以知道第一个db_element比第二个db_element多一个属性,我想得到的Sql查询结果为:
需要注意的是:不同db_element的属性可能彼此不同。各位大哥大姐帮帮小弟吧~
------解决方案--------------------
select db_element,
[:mcfloorn]=max(case when att_name=':mcfloorn' then att_value),
[:mcblockn]=max(case when att_name=':mcblockn' then att_value),
............
from tb group by db_element
------解决方案--------------------
------解决方案--------------------
http://topic.csdn.net/u/20081115/00/17588ccc-68be-4cac-8036-1bc3f78c7b3f.html
------解决方案--------------------
用pivot函数可以实现。或者用动态语句。
------解决方案--------------------
- SQL code
create table #tb(db_element varchar(10),att_name varchar(10),att_value int)insert into #tb select '张三','a',74 union allselect '张三','b',83 union allselect '张三','c',93 union allselect '李四','a',74 union allselect '李四','b',84 union allselect '李四','c',94 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'exec(@sql)drop table #tb----------------------------------de_element a b c李四 74 84 94张三 74 83 93---------------------(6 行受影响)(2 行受影响)
------解决方案--------------------
- SQL code
declare @sql varchar(1000)set @sql='select db_element'select @sql=@sql+',max(case when '''+att_name+''' then att_value else null end ['+att_name+']'from(select distinct att_name from tb)aset @sql=@sql+' from tb group by db_element'exec(@sql)