剑道第一仙

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

gbase&oracle行转列函数

转:https://blog.csdn.net/manonggeerdan/article/details/126299268?share_token=27704f7a-a864-49b2-b294-4586956169bd

一、group_concat(适用于mysql、gbase)

1、功能:

将group by产生的同一个分组中的值连接起来,返回一个字符串结果。

2、语法:
group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator ‘分隔符’] )

说明:通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。

测试

准备数据

复制代码
drop table if exists t_orders;

create table t_orders (
    id int primary key auto_increment,
    userId int,
    orderId varchar(20)
);

insert into t_orders(userId, orderId) values(1, '100');
insert into t_orders(userId, orderId) values(1, '101');
insert into t_orders(userId, orderId) values(1, '102');

insert into t_orders(userId, orderId) values(2, '200');
insert into t_orders(userId, orderId) values(2, '201');
insert into t_orders(userId, orderId) values(3, '300');
复制代码
-- (1)普通查询
select userId as 用户ID, orderId as 订单 from t_orders;  
-- (2)以 userId 分组,把 orderId 字段的值打印在一行,逗号分隔
select userId as 用户ID, group_concat(orderId) as 订单 from t_orders group by userId; 
-- (3)以 userId 分组,把 orderId 字段的值打印在一行,分号分隔
select userId as 用户ID, group_concat(orderId separator ';') as 订单 from t_orders group by userId;
-- (4)以 userId 分组,把 orderId 字段的值打印在一行,降序排列
select userId as 用户ID, group_concat(orderId order by orderId desc) as 订单列表 from t_orders group by userId;

(1):

(2):

 

(3):

 

(4):

 

二、group_concat(适用于Oracle)

-- (3)
select userId as 用户ID, LISTAGG(orderid, ',') WITHIN GROUP (ORDER BY orderid) as 订单 from t_orders group by userId; 

-- (4)
select LISTAGG(orderid, ',') WITHIN GROUP (ORDER BY orderid) as orderid
  from t_orders  t
order by orderid desc;

 

posted on   剑道第一仙  阅读(142)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示