Cannot use ORDER BY with DISTINCT and CONVERT

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aladiver
    New Member
    • May 2014
    • 2

    Cannot use ORDER BY with DISTINCT and CONVERT

    The following SQL code works fine if I don't use the CONVERT to make my column two characters wide. When using it as follows the error message reads:
    "ORDER BY items must appear in the select list if SELECT DISTINCT is specified." If I just use:
    SELECT DISTINCT MONTH(CTNoteDat e) it works fine.

    How can I run this query with the column width set and sort the results?

    Code:
    SELECT DISTINCT CONVERT(varchar(2),MONTH(CTNoteDate)) MO,
                    DATENAME(month,CTNoteDate) MONTH 
    FROM CTNotes WHERE YEAR(CTNoteDate)=2014
    ORDER BY MONTH(CTNoteDate)
    Thanks! ~GregM
    Last edited by Rabbit; May 14 '14, 05:30 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Please use code tags when posting code or formatted data.

    If you're going to use an ORDER BY with a DISTINCT, whatever is in the ORDER BY must also be in the SELECT.

    Therefore you have 2 solutions, include what's in your ORDER BY in your SELECT:
    Code:
    SELECT DISTINCT CONVERT(varchar(2),MONTH(CTNoteDate)) MO,
                    DATENAME(month,CTNoteDate) MONTH,
                    [b]MONTH(CTNoteDate)[/b]
    FROM CTNotes WHERE YEAR(CTNoteDate)=2014
    ORDER BY MONTH(CTNoteDate)
    Or change your ORDER BY to match the expression in the SELECT:
    Code:
    SELECT DISTINCT CONVERT(varchar(2),MONTH(CTNoteDate)) MO,
                    DATENAME(month,CTNoteDate) MONTH 
    FROM CTNotes WHERE YEAR(CTNoteDate)=2014
    ORDER BY [b]CONVERT(varchar(2),MONTH(CTNoteDate))[/b]

    Comment

    • aladiver
      New Member
      • May 2014
      • 2

      #3
      Very sorry about forgetting the code tags.

      Thank you very much -- it makes all the sense in the world, I just couldn't figure out HOW to include the select code in the order.

      Have a great day!

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        No problem, good luck with the rest of your project!

        Comment

        Working...