错误:如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中

时间:2013-07-29 16:08:49

标签: sql sql-server

我收到错误:

  

如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

对于此查询:

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 个答案:

答案 0 :(得分:3)

使用GROUP BY(以匹配注释中指定的排序顺序),而不是使用SELECT DISTINCT:

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]