排序时sql组出问题

时间:2011-02-14 09:57:11

标签: sql sql-order-by

我遇到错误问题:

列'EXT_Design_Standard.Name'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我想根据以下内容对记录进行分组: cl.EXT_Design_Standard_ID

我已根据(排序@directOfSort变量)

动态排序记录

任何人都知道如何解决以下问题?

DECLARE @fieldSort varchar(50) = 'Date Changed'
DECLARE @directionOfSort varchar(1) = 'D'

SELECT              min(cl.EXT_Design_Standard_ID)                                      AS [EXT_Design_Standard_ID],
                    ds.Name                                                         AS [Standards Name],
                    ds.Reference_Code                                               AS [Ref],
                    ( SELECT dbo.EXFN_StripHTML(ds.Description) )                   AS [Description],
                    (select replace(convert(varchar(20),cl.Change_On,106),' ','-')) + ' (' + CONVERT(VARCHAR(5) , cl.Change_On , 108)+ ')' AS [Date Changed],


FROM    EXT_Design_Standard_Change_Log cl      

INNER JOIN EXT_Design_Standard ds 
    on ds.EXT_Design_Standard_ID = cl.EXT_Design_Standard_ID      

INNER JOIN Contact_Summary cs
    on cs.Contact_ID = cl.Change_By

GROUP BY cl.EXT_Design_Standard_ID
ORDER BY 
    CASE WHEN @fieldSort ='Standards Name'
        THEN ROW_NUMBER() over (order by ds.Name) * 
            case when @directionOfSort = 'A' 
                THEN 1 ELSE -1 END
        END,
    CASE WHEN @fieldSort ='Ref'
        THEN ROW_NUMBER() over (order by ds.Reference_Code) * 
            case when @directionOfSort = 'A' 
                THEN 1 ELSE -1 END
        END,
    CASE WHEN @fieldSort ='Description'
        THEN ROW_NUMBER() over (order by ( SELECT dbo.EXFN_StripHTML(ds.Description) )) * 
            case when @directionOfSort = 'A' 
                THEN 1 ELSE -1 END
        END,
    CASE WHEN @fieldSort ='Date Changed'
        THEN ROW_NUMBER() over (order by cl.Change_On) * 
            case when @directionOfSort = 'A' 
                THEN 1 ELSE -1 END
        END

1 个答案:

答案 0 :(得分:3)

select子句需要按字段匹配。你只能直接使用group by子句中的字段,每个字段都不明确,你需要一个聚合函数。

在您的情况下,您具有按字段分组的聚合函数,但不适用于其他函数。

所以这个选择条款

SELECT              min(cl.EXT_Design_Standard_ID),
                    ds.Name,
                    ds.Reference_Code

不符合该组的条款

GROUP BY cl.EXT_Design_Standard_ID

假设你的group by子句是你真正想要的,你需要将select子句改编成这样的东西:

SELECT              cl.EXT_Design_Standard_ID,
                    min(ds.Name),
                    min(ds.Reference_Code)