S
S
Skilk2021-10-07 01:25:57
PostgreSQL
Skilk, 2021-10-07 01:25:57

Postgre Sql DISTINCT array with ORDER BY?

It is necessary to select unique comments from orders and display the first 3 words, sorted by 2 words.
Here's what I got

select DISTINCT (regexp_split_to_array(commend, E'\\s+'))[:3] from orders ORDER BY (regexp_split_to_array(commend, E'\\s+'))[2];

But it's not fulfilled
ERROR: in SELECT DISTINCT clause, ORDER BY expressions must be in the select list

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2021-10-07
@galaxy

select * from (
  select DISTINCT (regexp_split_to_array(commend, E'\\s+'))[:3] as words from orders
) t
 order by words[2]

https://www.db-fiddle.com/f/rKStiRfEcWZbJJ9ZJXGDZT/0
But keep in mind that in this case, SELECT DISTINCT will not select unique comments, but unique first three words.

A
Akina, 2021-10-07
@Akina

DISTINCT is actually a private form of GROUP BY. Therefore, it includes all restrictions for GROUP BY regarding the use of data source fields in window functions, post-selection and sorting expressions.
Therefore, use the output set field for sorting.

SELECT DISTINCT (regexp_split_to_array(commend, E'\\s+'))[:3] AS first_3_words
FROM orders 
ORDER BY first_3_words[2];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question