0

The goal of the query here was simplified, but it represents a complex one that I want to select all users fields from the subquery plus computing a SUM. So, this is an example only.

I'm doing a subquery because of a problem with SUM duplicate rows. Like recommended to do with this answer: https://stackoverflow.com/a/7351991/255932

But the problem is that subquery also selects a column "rating" from the table ratings and I can't select all users fields unless describing all users columns on parent select.

SELECT id, name, x, y, z ..., SUM(rating)

FROM
   (SELECT users.*, ratings.rating
    FROM users
    INNER JOIN ratings ON
    users.id = ratings.user_id
   )

GROUP BY users.id

I would like to know if there is a way to replace (id, name, x, y, z, ...) with a simple (users.*).

4

2 に答える 2

2

実は、とても簡単な方法が 2 つあります。

users.id主キーの場合:

SELECT u.*, sum(r.rating) AS total
FROM   users   u
JOIN   ratings r ON r.user_id = u.id
GROUP  BY u.id;

これが機能するには、Postgres 9.1 以降が必要です。この密接に関連した回答の詳細:
PostgreSQL - GROUP BY 句

users.id少なくとも一意の場合:

SELECT u.*, r.total
FROM   users u
JOIN  (
   SELECT user_id, sum(rating) AS total
   FROM   ratings
   GROUP  BY 1
    ) r ON r.user_id = u.id;

私が知っているどのバージョンでも動作します。テーブル全体またはその大部分を取得する場合は、通常、最初にグループ化し、後で結合する方が高速です。

于 2013-11-19T05:10:01.447 に答える
1

ちょっと、しかしそうではありません。回避策はありますが、サブクエリに別の方法でアプローチする必要があります。

SELECT (c.users).*, SUM(c.rating)

FROM
   (SELECT users, ratings.rating
    FROM users
    INNER JOIN ratings ON
    users.id = ratings.user_id
   ) c

GROUP BY c.users;
于 2013-11-19T04:05:31.743 に答える