1

我有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
4

1 回答 1

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 日本,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 FROM group_ex, group_ex2group_item_ex, group_item_ex, app_user, app_user2group_item_ex, app_user_role WHERE group_ex2group_item_ex.group_ex = group_ex.id AND group_ex2group_item_ex.items_id = group_item_ex.id = group_item_ex。

于 2013-06-17T08:09:52.787 回答