sql:聚合函数&字符串连接/串联
(我使用的是 postgres)
是否有任何适用于字符串的聚合函数?
的方式编写一个查询
select table1.name, join(' - ', unique(table2.horse)) as all_horses
from table1 inner join table2 on table1.id = table2.fk
group by table1.name
我想按照给定这两个表
| table1 | | table2 |
| id (pk) | name | | id (pk) | horse | fk |
+---------+-------+ +---------+---------+-------+
| 1 | john | | 1 | redrum | 1 |
| 2 | frank | | 2 | chaser | 1 |
| 3 | cigar | 2 |
:查询应该返回:
| name | all_horses |
+--------+-------------------+
| john | redrum - chaser |
| frank | cigar |
在任何字符串数据库中都存在符合 join
和 unique
的函数吗?
Possible Duplicate:
How to concatenate strings of a string field in a PostgreSQL ‘group by’ query?
(I'm using postgres)
Are there any aggregate functions that work on strings?
I want to write a query along the lines of
select table1.name, join(' - ', unique(table2.horse)) as all_horses
from table1 inner join table2 on table1.id = table2.fk
group by table1.name
Given these 2 tables:
| table1 | | table2 |
| id (pk) | name | | id (pk) | horse | fk |
+---------+-------+ +---------+---------+-------+
| 1 | john | | 1 | redrum | 1 |
| 2 | frank | | 2 | chaser | 1 |
| 3 | cigar | 2 |
The query should return:
| name | all_horses |
+--------+-------------------+
| john | redrum - chaser |
| frank | cigar |
Do functions that along the lines of join
and unique
exist in any DBs for strings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PostreSQL 9中有一个string_agg查询。我有一个地区表和一个部门表,其中一个地区有多个部门(例如法国)。我的示例查询是:
这给了我这样的行:
如果您想更改聚合字符串的顺序,事情会变得有点混乱。这是可行的,但我对任何具有不同的查询有一种病态的厌恶:
There is a string_agg query in PostreSQL 9. I have a table of regions and a table of departments, where there are multiple departments in a region (e.g. France). My sample query is:
This gives me rows like
Things get a bit messy if you wan to change the order of the aggregated string. This works, but I have a pathological dislike of any query with distinct: