如何编写将输入表中的多行连接到输出表中的一行的SQL查询 [英] How to write a SQL query that concatenates multiple rows from the input table into one row in the output table

查看:52
本文介绍了如何编写将输入表中的多行连接到输出表中的一行的SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下示例表:

C1     C2      C3
=================
A      21      S
A      22      S
A      23      S
A      24      T
B      25      S
B      26      S

如何编写SQL查询以提供以下输出:

How can I write an SQL query to give the following output:

COL1   COL2       COL3
======================
A      21,22,23      S
A      24            T
B      25,26         S

对于C1和C3相同的输入表中的所有行,我希望输出表中的一行将所有C2值串联在一起,并用逗号分隔.

For all rows in the input table where C1 and C3 are the same, I want one row in the output table that has all the C2 values concatenated, comma separated.

我正在使用Oracle数据库.

I'm working with an Oracle database.

推荐答案

这将是特定于数据库的答案,所以请使用您正在使用的数据库. Mysql很流行,因此这里是Mysql5答案:

This will be a database specific answer, so please what db you are using. Mysql is popular, so here is the Mysql5 answer:

select col1, group_concat(col2 SEPARATOR ','), col3 from tbl group by col1,col3;

这篇关于如何编写将输入表中的多行连接到输出表中的一行的SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆