MYSQL多列数据合并成1行

来源:互联网 发布:农村淘宝服务站有底薪 编辑:程序博客网 时间:2024/06/06 01:10

需求1:统计表1中type=1的条数

idnametype1张三12李四23王五24张三1

SQL:           

select  count(case when type=1 then 1 end)  from table1 

 

或者使用:  

select  count(id) from table1 where type=1 group by type


需求2:表1中type=1的name字段合并为1行

SQL:   

select group_concat(name) from table1 where type=1


需求3:表1中type=1的name字段合并为1行,同时去掉重复值


SQL:  

select group_concat(distinct name) from table1 where type=1


拓展:

表1(table1)

idnamesex1张三男   表2(table2)

idfav1喜欢打篮球1喜欢好姑凉表3(table3)

idach1语文85分1数学95分现在3个表中,根据id相互关联,现在要求把3张表的数据和为1条,查出 id为1的所有数据并且展示

SQL: 

select table1.id,table1.name,table1.sex,group_concat(table2.fav) as favs,group_concat(table3.ach) as achs from table1left join table2 on table1.id=table2.idleft join table3 on table1.id=table3.id

结果


idnamesexfavsachs1张三男喜欢打篮球,喜欢好姑凉语文85分,数学95分     



0 0
原创粉丝点击