SELECT
成都创新互联主营杏花岭网站建设的网络公司,主营网站建设方案,重庆App定制开发,杏花岭h5微信小程序开发搭建,杏花岭网站营销推广欢迎杏花岭等地区企业咨询
A,
GROUP_CONCAT( B SEPARATOR ',' ),
GROUP_CONCAT( C SEPARATOR ',' )
FROM
table_name
GROUP BY
A
1.GROUP_CONCAT()中的值为你要合并的数据的字段名;
2.SEPARATOR 函数是用来分隔这些要合并的数据的 ,' ' 中是你要用哪个符号来分隔,可以直接不填符号默认为空值;
2.必须要用GROUP BY 语句来进行分组管理,不然所有的数据都会被合并成一条记录
参考链接
1、创建测试表,
create table test_fee(userid number, feeid number, fee number);
2、插入测试数据
insert into test_fee values(1,1001,80);
insert into test_fee values(1,1002,70);
insert into test_fee values(1,1003,90);
insert into test_fee values(1,1004,60);
insert into test_fee values(2,1001,99);
insert into test_fee values(2,1002,66);
insert into test_fee values(2,1001,55);
3、查询表中所有记录,select t.*, rowid from test_fee t,
4、编写sql,按userid汇总,根据不同的feeid,进行行转列汇总,
select userid,
sum(case when feeid = 1001 then fee else 0 end) as fee_1001,
sum(case when feeid = 1002 then fee else 0 end) as fee_1002,
sum(case when feeid = 1003 then fee else 0 end) as fee_1003,
sum(case when feeid = 1004 then fee else 0 end) as fee_1004
from test_fee t
group by userid
参考以下sql
-- 测试一
-- 'abc|efg|hij|klm' 参数一:截取的字符串str
-- '|' 参数二:在截取的字符串str中查询目标字符x
-- 1 参数三:出现的位次n
-- 截取str中x出现n次之前的所有字符
-- 截取'abc|efg|hij|klm'中第一个'|'之前的所有字符 abc
SELECT SUBSTRING_INDEX('abc|efg|hij|klm', '|', 1)
-- 测试二
-- 'abc|efg|hij|klm' 参数一:截取的字符串str
-- '|' 参数二:在截取的字符串str中查询目标字符x
-- -1 参数三:当为负数时,则表示倒序的位次
-- 截取str后中x出现从后往前数n次之后的所有字符
-- 截取'abc|efg|hij|klm'中从后往前数第一个'|'之后的所有字符 klm
SELECT SUBSTRING_INDEX('abc|efg|hij|klm', '|', -1)
思路:先列出序号。用序号除4取余,余1就排在字段名称1下,余2就排在字段名称2下,楼主姐姐是这个意思吗?
select
case when ID%4=1 then 字段名称 end as 字段名称1
,case when ID%4=2 then 字段名称 end as 字段名称2
,case when ID%4=3 then 字段名称 end as 字段名称3
,case when ID%4=0 then 字段名称 end as 字段名称4
from
(select row_number() over(order by 字段名称) as ID, * from 表) as tb
使用存储过程。
方法如下:
1、先查询出表里面的列名称
2、行列转换
举例
1、查询student字段名
SELECT
a.colorder as _colOrder, --字段序号
a.name as _colName --字段名
FROM syscolumns a left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype='U' and d.name 'dtproperties'
left join syscomments e
on a.cdefault=e.id
left join sys.extended_properties g
on a.id=g.major_id AND a.colid = g.minor_id
where d.name='student' --所要查询的表
order by a.id,a.colorder
2、行列转换
SELECT
MAX (CASE WHEN SetupID = 1 THEN SetupName ELSE NULL END ) AS [1],
MAX (CASE WHEN SetupID = 2 THEN SetupName ELSE NULL END ) AS [2],
MAX (CASE WHEN SetupID = 3 THEN SetupName ELSE NULL END ) AS [3],
MAX (CASE WHEN SetupID = 4 THEN SetupName ELSE NULL END ) AS [4]
......
FROM table