2

我收到错误消息:

如果指定了 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]

我已经调查过了,没有定义案例似乎是一个常见问题,但我确实这样做了。我究竟做错了什么?

4

1 回答 1

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]
于 2013-07-29T16:27:26.273 回答