失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > sql server列转行怎么提高效率_行转列 列转行

sql server列转行怎么提高效率_行转列 列转行

时间:2018-07-29 05:57:38

相关推荐

sql server列转行怎么提高效率_行转列 列转行

1、行转列

所谓行转列,即将一行数据转成多行显示,或者说将多列数据转成一列显示。通常将转化后的列名为某一行中某一列的值,来识别原先对应的数据。具体如下:

通常的SQL实现用union来实现,如下。有些数据库有行转列的专用函数,具体可查询相关文档。

select id, name ,'Q1' jidu, (select q1 from fruit where id=f.id) xiaoshou from Fruit funionselect id, name ,'Q2' jidu, (select q2 from fruit where id=f.id) xiaoshou from Fruit funionselect id, name ,'Q3' jidu, (select q3 from fruit where id=f.id) xiaoshou from Fruit funionselect id, name ,'Q4' jidu, (select q4 from fruit where id=f.id) xiaoshou from Fruit f

2、列转行

所谓列转行,即将多行转为一行显示,或者说将一列转为多列显示。通常转化后将某一列distinct后的值作为列名,将此值对应的多行数据显示成一行。具体显示如下:

通常SQL实现可以通过嵌套子查询实现,即将多个子查询的子表通过条件以及拼凑字段,拼成大表。如:

select *from (select sum(nums) 苹果 from demo where name = '苹果'),(select sum(nums) 橘子 from demo where name = '橘子'),(select sum(nums) 葡萄 from demo where name = '葡萄'),(select sum(nums) 芒果 from demo where name = '芒果');

如果觉得《sql server列转行怎么提高效率_行转列 列转行》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。