gpt4 book ai didi

postgresql - 从具有 2 列的多个记录构造一个字符串

转载 作者:行者123 更新时间:2023-11-29 12:02:34 25 4
gpt4 key购买 nike

我准备了一个简单的SQL Fiddle对于我的问题-

在用 Pl/pgSQL 为 PostgreSQL 10.2 编写的文字游戏中,玩家的移动存储在表中:

CREATE TABLE words_scores (
mid bigint NOT NULL REFERENCES words_moves ON DELETE CASCADE,
gid integer NOT NULL REFERENCES words_games ON DELETE CASCADE,
uid integer NOT NULL REFERENCES words_users ON DELETE CASCADE,
word text NOT NULL CHECK(word ~ '^[A-Z]{2,}$'),
score integer NOT NULL CHECK(score >= 0)
);

这里填充了一些测试数据:

INSERT INTO words_scores (mid, gid, uid, word, score) VALUES
(230, 209, 7, 'XY', 5),
(230, 209, 7, 'XYZ', 15),
(230, 209, 7, 'XAB', 13);

在存储函数中,我需要生成一个字符串,其中包含玩家在某步棋中下的所有单词。

这接近我需要的并返回 XY, XYZ, XAB:

SELECT STRING_AGG(word, ', ') FROM words_scores WHERE mid=230;

但是我还需要将每个单词的分数放在括号中,如下所示:

XY (5), XYZ (15), XAB (13)

是否可以巧妙地使用 Aggregate Functions有可能实现吗?

最佳答案

使用 FORMAT(如 manual 中所述)在聚合之前格式化您的字符串:

SELECT STRING_AGG(FORMAT('%s (%s)', word, score), ', ') FROM words_scores WHERE mid=230;

这是 updated SQL Fiddle .

关于postgresql - 从具有 2 列的多个记录构造一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com