在 STRING_AGG 中分组

GROUP BY in STRING_AGG

我有一个 postgresql 查询来查找按优先级分组的数据库中的单词。它工作正常,看起来像这样:

select 
    min(w.text) as text,
    min(w.id) as w_id,
    count(distinct w.text),
    min(pwt.priority) as priority
from 
    word as w
join topic_word tw ON tw.word_id = w.id
join profile_word_topic pwt on pwt.topic_id = tw.topic_id and pwt."level" = tw."level" 
group by w.text 
order by min(pwt.priority), min(w.id)

结果看起来像这样并且有正确的字数 (10):

text |w_id|count|priority|
-----+----+-----+--------+
FOUR |   4|    1|       1|
FIVE |   5|    1|       1|
SIX  |   6|    1|       1|
SEVEN|   7|    1|       1|
EIGHT|   8|    1|       1|
NINE |   9|    1|       1|
TEN  |  10|    1|       1|
ONE  |   1|    1|       2|
TWO  |   2|    1|       2|
THREE|   3|    1|       2|

现在我想像这样将单词连接成一个字符串:

select 
    string_agg(distinct w.text, ','),
    count(distinct w.text),
    min(pwt.priority) as priority
from 
    word as w
join topic_word tw ON tw.word_id = w.id
join profile_word_topic pwt on pwt.topic_id = tw.topic_id and pwt."level" = tw."level" 
group by pwt.priority 
order by min(pwt.priority), min(w.id)

但是现在有些词重复了,总词数是12:

string_agg                        |count|priority|
----------------------------------+-----+--------+
EIGHT,FIVE,FOUR,NINE,SEVEN,SIX,TEN|    7|       1|
FIVE,FOUR,ONE,THREE,TWO           |    5|       2|

如何去掉重复的单词?我该如何解决排序问题?

如果你能告诉我如何在 SQLAlchemy 中实现这一点,加分,但这是次要的,因为我相信移植它应该是直截了当的。

感谢您提前输入:-)

我现在可以使用这样的子查询了:

select 
    string_agg(text, ','),
    count(text),
    min(priority)
from (
    select 
        min(w.text) as text,
        min(w.id) as w_id,
        count(distinct w.text),
        min(pwt.priority) as priority
    from 
        word as w
    join topic_word tw ON tw.word_id = w.id
    join profile_word_topic pwt on pwt.topic_id = tw.topic_id and pwt."level" = tw."level" 
    group by w.text 
    order by min(pwt.priority), min(w.id)
) sub
group by priority

现在我得到了正确的结果(正确的字数和顺序是正确的):

string_agg                        |count|min|
----------------------------------+-----+---+
FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN|    7|  1|
ONE,TWO,THREE                     |    3|  2|

所以理论上我的问题得到了回答。 但我想知道这是否可以在没有子查询的情况下实现。