如何在Postgresql中返回一列中具有相同值的行组

  • 本文关键字:一列 Postgresql 返回 postgresql
  • 更新时间 :
  • 英文 :


我正在尝试编写一个查询,该查询将返回按相同名字分组的行,其中姓氏为LIKE"一些搜索字符串%〃;

例如,如果我搜索姓氏LIKE 'Smi%',我想把这个结果返回

{
[{1, tofu_spice, Joe, Smith}, {2, jsmith, Joe, Smithy}],
[{3, smirthy11, Jack, Smirth}, {5, jackal, Jack, Smiles}],
} 
f_namel_nameSmithSmithSmirth微笑Allie
id用户名
1tofu_spiceJoe
2jsmithJoe
3smirthy11插孔
5豺狼杰克
6kevsJack
7rb2015罗伯布朗
8luigi191罗布布兰

手动参考: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;

最新更新