Home > Enterprise >  MySQL Sort by multiple columns (3) with some specific rules
MySQL Sort by multiple columns (3) with some specific rules

Time:03-01

the question has been posted but marked as duplicate. Please note that I am aware of simple ORDER BY with multiple columns and with a window function MIN() for example for a simple case of two columns.

Suppose I have a table so-called Contact (Table 1.) What I want to achieve is to sort first by Status than within the result, sort Client by CalledAt (keep Client close together by CreatedAt while keeping the order of Client as-is from the first sort)

Bellow my explanation, please suggest a better question/explanation if it makes things clearer.

Thank you,

Step 0:

ID User Client CalledAt Status
1 B Y 2022-02-07 Do not answer
2 A Y 2022-02-09 Answer
3 A X 2022-02-08 Answer
4 B X 2022-02-10 Do not answer
5 A X 2022-02-06 Answer
6 B Z 2022-02-11 Do not answer

Step 1: Sort by Status

ID User Client CalledAt Status
2 A Y 2022-02-09 Answer
3 A X 2022-02-08 Answer
5 A X 2022-02-06 Answer
1 B Y 2022-02-07 Do not answer
4 B X 2022-02-10 Do not answer
6 B Z 2022-02-11 Do not answer

Now the list of clients are: YXXYXZ, I want to keep the client Y first, because it appeared first in the list then X because it appeared first after all the Y then Z...

The list of clients should be YYXXXZ. Within the client, they should be sorted by CreatedAt.

Step 2: Line 1 is moved above line 2 becase it shares the same client Y but with a smaller (sonner) CalledAt. Line 5 is moved above line 3 and line 4 is move bellow line 3

ID User Client CalledAt Status
1 B Y 2022-02-07 Do not answer
2 A Y 2022-02-09 Answer
5 A X 2022-02-06 Answer
3 A X 2022-02-08 Answer
4 B X 2022-02-10 Do not answer
6 B Z 2022-02-11 Do not answer

CodePudding user response:

In MySQL 5.x

SELECT
  yourTable.*
FROM
  yourTable
INNER JOIN
(
  SELECT
    client,
    MIN(id)       AS min_id,
    MIN(Status)   AS min_status
  FROM
    yourTable
  GROUP BY
    client
)
  AS client
    ON client.client = yourTable.client
ORDER BY
  client.min_status,
  client.min_id,
  yourTable.calledAt
  • Related