1

I have a table that contains a name of a color (teal, for example) and the associated primary color (blue). Sometimes a color entry can be the same as its associated primary color (red, red).

How can I do a GROUP BY PRIMARY_COLOR where the COLOR for each group are in alphabetical order...except when a COLOR and PRIMARY_COLOR match -- this entry needs to be at the top of the grouping.

Example:

COLOR    PRIMARY_COLOR
------------------------
teal     blue
magma    red
sky      blue
red      red
magenta  red

should result...

COLOR    PRIMARY_COLOR
------------------------
sky      blue
teal     blue
red      red
magenta  red
magma    red
1
  • 1
    are you sure you need a group by? i think you are just doing an order by Commented May 6, 2011 at 21:39

3 Answers 3

4

Order by (ASSOCIATEDCOLOR = COLOR), ASSOCIATEDCOLOR

Sign up to request clarification or add additional context in comments.

Comments

1
ORDER BY CASE WHEN COLOR=PRIMARY_COLOR THEN 0 ELSE 1 END, PRIMARY_COLOR

Comments

0
SELECT color, primary_color
FROM colors
ORDER BY
    primary_color,
    color LIKE primary_color DESC,
    color

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.