Sort select displaying something at the end after sorting

Asked

Viewed 98 times

4

I have a table called Tabela1 and another call Tabela2:

Tabela 1             Tabela2
Indice, pessoa_id    sts, pessoa_id

The index goes from 0 to 10, and sts can be ON-LINE, OFF-LINE OR ON-LINE-PAUSADO.

I wish that when I gave the select, come back ordered, but if any of these people are with the sts equal to 'online-paused', come at the end of the select.

Example:

indice, pessoa_id, sts
4     , 2        , 'ON-LINE'
5     , 2        , 'ON-LINE'
6     , 2        , 'ON-LINE'
8     , 2        , 'ON-LINE'
1     , 2        , 'ON-LINE-PAUSADO'
2     , 2        , 'ON-LINE-PAUSADO'
  • This makes it clearer: http://prntscr.com/mn5fr8

  • But ON-LINE is also being presented in your example... I don’t understand what you want to do. If it is ON-LINE-PAUSADO need to show, if it is not show anything?

  • It worked, thanks for your time, hug :D https://i.stack.Imgur.com/oXNEr.png

3 answers

2


You need to sort by status and then by descending index column.

Your query would look like this:

SELECT
    t1.indice,
    t1.pessoa_id,
    t2.sts
FROM
    tabela1 t1
INNER JOIN tabela2 t2 ON t1.pessoa_id = t2.pessoa_id
ORDER BY
    t2.sts, t1.Indice DESC

This form will work because the name of your status is in alphabetical order, however, if you have more status, you can create a new column and sort it by adding an integer in the order of the status you want to return (1, 2, 3...).

Example:

ALTER TABLE tabela2
ADD COLUMN ordem_status INT

And in the same query above, you will sort through this new column, getting:

ORDER BY t2.ordem_status, t1.Indice DESC

2

Something should not be right in your definition of tables, because in Tabela 2 must be the column Indice, otherwise linking with each other the result would not be correct.


Assuming that the Tabela 2 there is the column Indice, the following query returns you what you want:

SELECT      T1.pessoa_id
        ,   T2.indice
        ,   T2.sts
FROM        tbl1 T1
INNER JOIN  tbl2 T2 ON T2.pessoa_id = T1.pessoa_id
ORDER BY    (   CASE T2.sts 
                WHEN 'ON-LINE'  THEN 1 
                WHEN 'OFF-LINE' THEN 2 
                ELSE 3 
                END
            )
        ,   T2.indice

If in the future you have another kind of status, just manage the ordering by adding or changing the states (or the numbering for each one).

  • I have 3 Tables to Person, Access and List The List is just a table used to list all people on the scale where in 1 scale I can have n lists of people Person: ID, Access_id(fk) Access Sts List Personal List_id, Indice I want to sort all people by indices, but if Sts != on line is at the end I believe I’ve already given a light on how to do with the case in order by, thank you :D

1

Simply add the syntax to your query:

. . .  order by Tabela2.sts, Tabela1.Indice

Browser other questions tagged

You are not signed in. Login or sign up in order to post.