如何在 Postgres 中使用带有通配符的分组依据

Oka*_*eno 6 sql postgresql group-by

我在 Postgres 中使用此代码时遇到问题。我想获取用户表中的所有字段,但仅按 id 分组。这在 MySQL 和 SQLite 上运行良好,但在谷歌搜索后我发现这种行为不是标准的一部分。

SELECT u.*, p.*, count(o.id) AS order_count
FROM shop_order AS o
LEFT JOIN user AS u ON o.user_id = u.id
LEFT JOIN userprofile AS p ON p.user_id = u.id
WHERE o.shop_id = <shop_id>
GROUP BY u.id
Run Code Online (Sandbox Code Playgroud)

(请注意,它<shop_id>是以编程方式传递的,因此您可以轻松地将其替换为任何整数。)

这是我收到的错误

column "u.id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)

我是一个 SQL 新手,所以如果这是显而易见的,请保持温和:)

And*_*mar 2

您可以使用row_number将结果限制为每个用户一行:

select  *
from    (
        select  row_number() over (partition by u.id) as rn
        ,       *
        join    user u
        on      sub.user_id = u.id
        join    shop_order so
        on      so.user_id = u.id
        left join
                userprofile up
        on      up.user_id = u.id
        where   so.shop_id = <shop_id>
        ) as SubQueryAlias
where   rn = 1
Run Code Online (Sandbox Code Playgroud)

子查询是必需的,因为 Postgres 不允许像子句row_number中那样的窗口函数where