我正在通过具有只读访问权限的pgAdmin 4使用Postgres 9.5,并且我试图编写一个select查询,该查询将从这种形式转换数据:
+----------+-------------------+--------------------+----------------+
| username | filters | groups | roles |
+----------+-------------------+--------------------+----------------+
| kd24 | Khaled <27607> | V1 | NewsStand User |
| kd24 | Khaled <27607> | V1 | User |
| kd24 | Khaled <27607> | Weekly KPIs | NewsStand User |
| kd24 | Khaled <27607> | Detailed Sales | User |
| kd24 | Khaled <27607> | Qanz Monthly Group | User |
| kd24 | Khaled <27607> | Detailed Sales | NewsStand User |
| kd24 | Khaled <27607> | Qanz Monthly Group | NewsStand User |
| kd24 | Khaled <27607> | Weekly KPIs | User |
| kd24 | Khaled <F_27607> | Weekly KPIs | User |
| kd24 | Khaled <F_27607> | Weekly KPIs | NewsStand User |
| kd24 | Khaled <F_27607> | Qanz Monthly Group | NewsStand User |
| kd24 | Khaled <F_27607> | Detailed Sales | User |
| kd24 | Khaled <F_27607> | V1 | User |
| kd24 | Khaled <F_27607> | Detailed Sales | NewsStand User |
| kd24 | Khaled <F_27607> | Qanz Monthly Group | User |
| kd24 | Khaled <F_27607> | V1 | NewsStand User |
| kd24 | khaled.d | Weekly KPIs | User |
| kd24 | khaled.d | V1 | NewsStand User |
| kd24 | khaled.d | Detailed Sales | NewsStand User |
| kd24 | khaled.d | Qanz Monthly Group | NewsStand User |
| kd24 | khaled.d | Weekly KPIs | NewsStand User |
| kd24 | khaled.d | V1 | User |
| kd24 | khaled.d | Detailed Sales | User |
| kd24 | khaled.d | Qanz Monthly Group | User |
+----------+-------------------+--------------------+----------------+
此表单:
+----------+-----------------------------------------------+-----------------------------------------------------+---------------------+
| username | filters | groups | roles |
+----------+-----------------------------------------------+-----------------------------------------------------+---------------------+
| kd24 | Khaled <27607>, Khaled <F_27607>,khaled.d | V1, Weekly KPIs, Detailed Sales, Qanz Monthly Group | NewStand User, User |
+----------+-----------------------------------------------+-----------------------------------------------------+---------------------+
请注意,列过滤器,组和角色中的值可能会更改。
是可以执行该操作的postgres选择脚本吗?
非常感谢!
答案 0 :(得分:2)
您可以将distinct
关键字与array_agg之类的聚合函数一起使用,以从每个列中收集不同的值:
select
array_agg(distinct username) as username,
array_agg(distinct filters) as filters,
array_agg(distinct groups) as groups,
array_agg(distinct roles) as groups
from YourTable;
答案 1 :(得分:2)
尝试一下
SELECT
username,
string_agg(DISTINCT filters,',') as filters,
string_agg(DISTINCT groups,',') as roles,
string_agg(DISTINCT roles,',') as groups
FROM
table1
GROUP BY
username;