I have a lot of difficulties in expressing in words what I want (this heading is the best I could think of), itโs easier with the diagram, but I will try to explain myself first.
I want to order a request using this rule:
- Group the query by the Group column.
- Place the โPrimaryโ of each group on top of its group.
- If the strings have the same "Name" as the primary, place it immediately after their primary.
- Put the rest of the lines by their names
Points 1, 2, and 4 are trivial. A simple ORDER BY to trick. But I have never seen a query with point 3.
I read a little about RANK () and ROW_NUMBER () , tried them, but I was not able to create the output that I want. I begin to doubt if this is possible.
Anyway, here is a piece of SQL to test it. Any help is appreciated. If you can find the best conditions to describe this, feel free to fix it.
CREATE TABLE
(
COL_GROUP INT,
COL_PRIMARY BIT,
COL_NAME VARCHAR(3)
)
INSERT INTO
VALUES
(1,1,'AAA'),
(2,0,'BBB'),
(2,1,'BBB'),
(1,0,'BBB'),
(1,0,'AAA'),
(2,0,'AAA')
SELECT
*
FROM
ORDER BY
COL_GROUP,
COL_PRIMARY DESC,
COL_NAME
DROP TABLE
This gives this result:
COL_GROUP COL_PRIMARY COL_NAME
1 1 AAA
1 0 AAA
1 0 BBB
2 1 BBB
2 0 AAA
2 0 BBB
I want this output:
COL_GROUP COL_PRIMARY COL_NAME
========= =========== ========
1 1 AAA
1 0 AAA
1 0 BBB
2 1 BBB
2 0 BBB
2 0 AAA