如何按一列分组并按另一列排序?

时间:2016-03-01 01:41:05

标签: sql sql-server tsql

SQL n00b在这里。所以我有一个像

这样的程序
GO 
CREATE PROCEDURE GetSectionAverages
    @partner_id UNIQUEIDENTIFIER,
    @survey_id INT
AS
    BEGIN
        SELECT S.title AS section_title, AVG(A.val) AS answer_average
        FROM 
            Sections AS S INNER JOIN Subsections AS SS ON S.Id=SS.section_id
                          INNER JOIN Questions AS Q ON SS.id=Q.subsection_id
                          LEFT OUTER JOIN Answers AS A ON A.question_id=Q.id
                          INNER JOIN Partners AS P ON A.partner_id=P.id
            WHERE S.survey_id=@survey_id AND P.id=@partner_id
            GROUP BY S.title
    END
GO

但是如何返回结果我希望它们按id表的Sections列排序,我无法弄清楚如何做到这一点。换句话说,如果这些部分是

id |   title
--------------
 1 | "Banana" 
 2 | "Apple"
 3 | "Melon"

然后结果将是

"Banana" | 69.2
"Apple"  | 15.0
"Melon"  | 99.9

相反,我希望结果按字母顺序显示标题,如

"Apple"  | 15.0
"Banana" | 69.2
"Melon"  | 99.9

我已尝试添加ORDER BY条款,但我收到错误,因为我不知道在进行分组时将它们放在哪里。

1 个答案:

答案 0 :(得分:3)

你基本上有两个选择。您可以在GROUP BY

中添加ID
GROUP BY S.title, S.id
ORDER BY S.id

或者您可以在ORDER BY

中使用聚合函数
GROUP BY S.title
ORDER BY MIN(S.id)