[英]String concatenation operator in Oracle, Postgres and SQL Server
[英]Postgres: string aggregation and concatenation
如果我有这样的查询:
SELECT
u.client_code,
max(d.created_at) as last_document_created_at,
u.brand_id,
t.name as template_name,
count(d)
FROM users u
INNER JOIN documents d ON u.id = d.user_id
INNER JOIN templates t ON t.id = d.template_id
GROUP BY 1, 3, 4
返回如下信息:
client_code last_document_created_at brand_id template_name count
---------------------------------------------------------------------
client1 2017-12-06 10:03:47 +1100 39 newsletter_r 1
client1 2017-12-05 15:23:24 +1100 39 Other media 5
client2 2017-12-21 17:07:11 +1100 39 newsletter_r 4
client3 2018-01-11 12:10:43 +1100 39 newsletter_r 2
client3 2017-12-06 11:45:21 +1100 39 Other media 1
我可以使用哪些选项来连接template_name
和count
字段,以使每个用户(用u.client_code
表示)都在一行上? 我知道我可以像这样将string_agg
称为该列:
...
string_agg(distinct t.name, ', ') as template_name,
...
但这当然会破坏各自的数量:
newsletter_r, Other media 6
更新
我可以这样做:
string_agg(concat_ws(': ', t.name::text, count(d)::text), ', ') as template_count
但这给了我一个错误:
aggregate function calls cannot be nested LINE 5: string_agg(concat_ws(': ', t.name::text, count(d)::text)... ^ : SELECT u.client_code,
不确定要如何设置串联字段的格式,但是是否尝试将原始查询放入子查询并对其应用string_agg
? 像这样:
SELECT client_code, STRING_AGG(template_name || template_count, ',')
FROM (
SELECT
u.client_code,
MAX(d.created_at) AS last_document_created_at,
u.brand_id,
t.name AS template_name,
COUNT(d) AS template_count
FROM users u
INNER JOIN documents d ON u.id = d.user_id
INNER JOIN templates t ON t.id = d.template_id
GROUP BY 1, 3, 4
) src
GROUP BY client_code
我尚未测试过,因此您可能会遇到一些语法错误。 让我知道是否可行。
我想你想要这样的东西:
SELECT u.client_code,
max(d.created_at) as last_document_created_at,
u.brand_id,
string_agg(t.name, ',') as template_name,
count(distinct d.id)
FROM users u INNER JOIN
documents d
ON u.id = d.user_id INNER JOIN
templates t
ON t.id = d.template_id
GROUP BY 1, 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.