2013-07-29 192 views
2

我收到錯誤:錯誤:ORDER BY項目必須出現在選擇列表中,如果SELECT DISTINCT指定

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

對於此查詢:

SELECT DISTINCT 
    [Theme].[Name], [ThemeType].[Type] 
FROM 
    [Theme] 
LEFT OUTER JOIN 
    [ThemeType] ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType] 
JOIN 
    [ProductTheme] ON [ProductTheme].[ThemeId]=[Theme].[PK_Theme] 
WHERE 
    ProductTheme.ProductID LIKE '%' 
    AND ProductTheme.ThemeId = Theme.PK_Theme 
    AND COALESCE([THEME].[THEMETYPEID], 'null') LIKE '%[0-9]%' 
ORDER BY 
    CASE WHEN [THEMETYPE].[TYPE] IS NULL 
      THEN 0 
      ELSE 1 
    END, [THEMETYPE].[TYPE] 

我已經考慮它,而不是定義案例似乎是一個常見問題,但我確實如此。我究竟做錯了什麼?

+1

@大衛:嘗試包括你在ORDER BY到整個SELECT CASE語句以及 –

+0

什麼你的'ThemeType.Type'列有哪些值?你可能會在'SELECT'和'ORDER BY'子句中使用'ISNULL(ThemeType.Type,-99999)'來確保'NULL'先出現嗎? –

+1

我不明白'CASE' *表達式*的用途。無論如何不會'NULL'排序? –

回答

3

而不是使用SELECT DISTINCT,使用GROUP BY(以匹配註釋指定的排序順序):

SELECT 
    [Theme].[Name], [ThemeType].[Type] 
FROM 
    [Theme] 
LEFT OUTER JOIN 
    [ThemeType] ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType] 
JOIN 
    [ProductTheme] ON [ProductTheme].[ThemeId]=[Theme].[PK_Theme] 
WHERE 
    ProductTheme.ProductID LIKE '%' 
    AND ProductTheme.ThemeId = Theme.PK_Theme 
    AND COALESCE([THEME].[THEMETYPEID], 'null') LIKE '%[0-9]%' 
GROUP BY 
    [Theme].[Name], [ThemeType].[Type] 
ORDER BY 
    CASE WHEN [ThemeType].[Type] IS NULL 
      THEN 0 
      ELSE 1 
    END, [Theme].[Name] 
相關問題