0
点赞
收藏
分享

微信扫一扫

MYSQL列转行

建表语句:

1

2

3

4

5

6

7

8

9


CREATE TABLE tb_score1(

id INT(11) NOT NULL auto_increment,

userid VARCHAR(20) NOT NULL COMMENT '用户id',

cn_score DOUBLE COMMENT '语文成绩',

math_score DOUBLE COMMENT '数学成绩',

en_score DOUBLE COMMENT '英语成绩',

po_score DOUBLE COMMENT '政治成绩',

PRIMARY KEY(id)

)ENGINE = INNODB DEFAULT CHARSET = utf8;


插入数据:

1

2

3


INSERT INTO tb_score1(userid,cn_score,math_score,en_score,po_score) VALUES ('001',90,92,80,0);

INSERT INTO tb_score1(userid,cn_score,math_score,en_score,po_score) VALUES ('002',88,90,75.5,0);

INSERT INTO tb_score1(userid,cn_score,math_score,en_score,po_score) VALUES ('003',70,85,90,82);


查询数据表中的内容(即转换前的结果)

1


SELECT * FROM tb_score1


MYSQL列转行_mysql

转换后:

MYSQL列转行_#include_02

本质是将userid的每个科目分数分散成一条记录显示出来。

直接上SQL:

1

2

3

4

5

6

7

8


SELECT userid,'语文' AS course,cn_score AS score FROM tb_score1

UNION ALL

SELECT userid,'数学' AS course,math_score AS score FROM tb_score1

UNION ALL

SELECT userid,'英语' AS course,en_score AS score FROM tb_score1

UNION ALL

SELECT userid,'政治' AS course,po_score AS score FROM tb_score1

ORDER BY userid


这里将每个userid对应的多个科目的成绩查出来,通过UNION ALL将结果集加起来,达到上图的效果。

/*
* The task state array is a strange "bitmap" of
* reasons to sleep. Thus "running" is zero, and
* you can test for combinations of others with
* simple bit tests.
*/
static const char * const task_state_array[] = {
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"t (tracing stop)", /* 8 */
"X (dead)", /* 16 */
"Z (zombie)", /* 32 */
};
  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<stdlib.h>
  4 int main()
  5 {
  6   pid_t id =fork();
  7   if(id==0)
  8   {
  9     int cnt=5;
 10     while(cnt)
 11     {
 12       printf("child,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt);                                                                                                                        
 13         --cnt;
 14       sleep(1);
 15     }
 16     exit(0);
 17   }
 18   else
 19   {
 20     while(1)
 21     {
 22       printf("parent,pid:%d,ppid:%d\n",getpid(),getppid());
 23       sleep(1);
 24     }
 25   }
 26   return 0;
 27 }

总结

到此这篇关于搞定mysql行转列的7种方法以及列转行的文章就介绍到这了,更多相关mysql行转列及列转行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

举报

相关推荐

0 条评论