Group By似乎没有像我预期的那样工作(SQL Server)

时间:2016-08-01 12:19:45

标签: sql sql-server group-by

我有以下查询:

SELECT 
    AVG(CAST(RATING AS NUMERIC(18, 2))) AS AVERAGE,
    QUESTIONID,
    COUNT(QUESTIONID) AS COUNT
FROM
    AnswersRating
WHERE 
    SURVEYID IN (SELECT ID
                 FROM SURVEYS
                 WHERE FLIGHTDATAID = 7277)
GROUP BY 
    QUESTIONID;

我得到了这个结果:

AVERAGE  QUESTIONID COUNT
-------------------------
3.606060 115        99
4.303030 109        99
2.969696 118        99
3.818181 112        99
2.545454 113        99
3.787878 121        99
3.606060 110        99
2.363636 119        99
3.515151 116        99
3.272727 117        99
4.242424 111        99
3.909090 120        99
2.333333 114        99

哪个好,除了QUESTIONID行之外的所有行都没有按照ID从最低到最高排序,这就是我想要的。我在另一个航班上做了完全相同的查询,其中事情正确显示:

AVERAGE  QUESTIONID COUNT
--------------------------
3.000000 109        1
3.000000 110        1
3.000000 111        1
3.000000 112        1
0.000000 113        1
0.000000 114        1
3.000000 115        1
0.000000 116        1
3.000000 117        1
3.000000 118        1
0.000000 119        1
3.000000 120        1
3.000000 121        1

我做错了什么?

2 个答案:

答案 0 :(得分:4)

为什么不使用Order By?分组并不意味着订购。

ORDER BY QUESTIONID;

答案 1 :(得分:4)

如果您需要特定的结果订单,则必须在ORDER BY in子句顺序之后指定GROUP BY。这两个条款并不相互排斥:

SELECT AVG(CAST(RATING AS NUMERIC(18, 2))) AS AVERAGE,
     QUESTIONID,
     COUNT(QUESTIONID) AS COUNT
FROM AnswersRating
WHERE SURVEYID IN
(
   SELECT ID
   FROM SURVEYS
   WHERE FLIGHTDATAID = 7277
)
GROUP BY QUESTIONID
ORDER BY QUESTIONID;

您的第二个查询是按顺序返回结果。