1

I have a table

| group | col1   | col2 |
| 1     | test1  | val1 |
| 1     | test2  | val2 |
| 3     | test3  | val3 |
| 3     | test4  | val4 |

I need to select rows by priority. For example, if row has col1 value as test1 so show it. If it's not then show test2. Don't remember about group. Just if values in one group. I expect this result:

| group | col1   | col2 |
| 1     | test1  | val1 |
| 3     | test3  | val3 |
1
  • 1
    Tag your question with the database you are using. Commented Jun 3, 2020 at 11:26

3 Answers 3

2

In standard SQL, you seem to want:

select t.*
from t
order by (case when col1 = 'test1' then 1
               when col2 = 'test2' then 2
               else 3
          end)
fetch first 1 row only;

EDIT:

For the revised question, you can use distinct on:

select distinct on (group) t.*
from t
order by group,
         (col1 = 'test1') desc,
         (col1 = 'test2') desc;
Sign up to request clarification or add additional context in comments.

2 Comments

It returns only one row. I need the result as I mentioned in post.
@MargulanZharkenov . . . You edited the question after I answered.
1

Please use below query,

select * from 
(select group, col1, col2, row_number() over (partition by group order by col1) as rnk
from table) where rnk = 1;

2 Comments

In this query I can't change the priority. Maybe I want to be the first priority value "test2".
In that case you can have order by descending. Use this function row_number() over (partition by group order by col1 desc). Use desc key word in the order by clause
1

This is the query that work!

select * from 
(select group, 
        col1, 
        col2, 
        row_number() over (partition by group order by (case when col1 = 'test1' then 2
               when col1 = 'test2' then 1
               else 3
          end)) as rnk
from test) AS tab1 where rnk = 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.