我正在尝试编写一个查询,该查询将返回按相同名字分组的行,其中姓氏为LIKE"一些搜索字符串%〃;
例如,如果我搜索姓氏LIKE 'Smi%'
,我想把这个结果返回
{
[{1, tofu_spice, Joe, Smith}, {2, jsmith, Joe, Smithy}],
[{3, smirthy11, Jack, Smirth}, {5, jackal, Jack, Smiles}],
}
id | 用户名 | f_namel_name||
---|---|---|---|
1 | tofu_spice | Joe | Smith|
2 | jsmith | Joe | Smith|
3 | smirthy11 | 插孔 | Smirth|
5 | 豺狼 | 杰克 | 微笑|
6 | kevs | Jack | Allie|
7 | rb2015 | 罗伯 | 布朗 |
8 | luigi191 | 罗布 | 布兰 |
手动参考:https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-骨料
BEGIN;
CREATE temp TABLE users (
id bigint,
username text,
f_name text,
l_name text
);
INSERT INTO users
VALUES (1, 'tofu_spice', 'Joe', 'Smith'),
(2, 'jsmith', 'Joe', 'Smithy'),
(3, 'smirthy11', 'Jack', 'Smirth'),
(5, 'jackal', 'Jack', 'Smiles'),
(6, 'kevs', 'Jack', 'Allie'),
(7, 'rb2015', 'Rob', 'Brown'),
(8, 'luigi191', 'Rob', 'Bran');
COMMIT;
SELECT
array_agg(users.* ORDER BY id) AS grouped_user
FROM
users
WHERE
l_name LIKE 'Smi%'
GROUP BY
f_name
HAVING
cardinality(array_agg(users.* ORDER BY id)) > 1;