我有Postgresql 9.2
并且想知道如何对此查询进行分组,以便我们只获得一个用户,并希望按app_user2group_item_ex.user_id或app_user.id分组,这样我就可以获得3行(而不是6行)每个user_id一行)和日本,美国和新加坡列中的数据类似于希望的结果。
有人可以让我知道如何使用Group By per app_user.id这样做我得到一个信息,其中包含数字的所有其他列我必须添加到Group By or Agregate
。
如果我可以获得有关此特定案例的一些信息,因为我是postgresql的新手。
SELECT
group_ex2group_item_ex.group_ex,
group_ex2group_item_ex.items_id,
group_ex.id,
group_ex.name,
group_ex.group_id,
group_item_ex.id,
group_item_ex.name,
group_item_ex.group_id,
app_user.first_name,
app_user.id,
app_user2group_item_ex.user_id,
app_user2group_item_ex.group_item_id,
(CASE WHEN group_ex."name" = 'Japan' THEN group_item_ex.name END) AS Japan,
(CASE WHEN group_ex."name" = 'USA' THEN group_item_ex.name END) AS USA,
(CASE WHEN group_ex."name" = 'Singapore' THEN group_item_ex.name END) AS Singapore
FROM
public.group_ex,
public.group_ex2group_item_ex,
public.group_item_ex,
public.app_user,
public.app_user2group_item_ex
WHERE
group_ex2group_item_ex.group_ex = group_ex.id AND
group_ex2group_item_ex.items_id = group_item_ex.id AND
group_item_ex.group_id = group_ex.group_id AND
app_user.id = app_user2group_item_ex.user_id AND
app_user2group_item_ex.group_item_id = group_item_ex.id;
查询结果:
group_ex items_id id name group_id id name group_id first_name id user_id group_item_id Japan USA Singapore
1 1 1 Japan 1 1 Nagoya 1 Will 1 1 1 Nagoya
1 2 1 Japan 1 2 Kyoto 1 Novak 3 3 2 Kyoto
2 3 2 USA 2 3 New York 2 Will 1 1 3 New York
2 4 2 USA 2 4 Los Angeles 2 Bos 2 2 4 Los Angeles
3 5 3 Singapore 3 5 Pudong 3 Bos 2 2 5 Pudong
3 6 3 Singapore 3 6 Center 3 Novak 3 3 6 Center
希望的结果(没有在此列出所有字段,因为我不需要它们):
first_name id user_id Japan USA Singapore
Will 1 1 Nagoya New York
Novak 3 3 Kyoto Center
Bos 2 2 Los Angeles Pudong
答案 0 :(得分:0)
我能够解决这个问题:
选择 app_user.first_name || ''|| app_user.last_name AS用户, app_user.email, app_user.phone_number, app_user.user_role_id, app_user.active, app_user.username, app_user.id, max((CASE WHEN group_ex。“name”='Japan'THEN group_item_ex.name END))AS Japan, max((CASE WHEN group_ex。“name”='USA'THEN group_item_ex.name END))AS USA, max((CASE WHEN group_ex。“name”='Singapore'THEN group_item_ex.name END))AS Singapore, app_user_role.id, app_user_role.name 从 group_ex, group_ex2group_item_ex, group_item_ex, APP_USER, app_user2group_item_ex, app_user_role 哪里 group_ex2group_item_ex.group_ex = group_ex.id AND group_ex2group_item_ex.items_id = group_item_ex.id AND group_item_ex.group_id = group_ex.group_id AND app_user.id = app_user2group_item_ex.user_id AND app_user2group_item_ex.group_item_id = group_item_ex.id AND app_user.user_role_id = app_user_role.id group by app_user.id,app_user.first_name,app_user_role.id,app_user_role.name 按app_user.id排序