Group By doesn't seem to work as I expected (SQL Server) -


i have following query:

select      avg(cast(rating numeric(18, 2))) average,     questionid,     count(questionid) count     answersrating      surveyid in (select id                  surveys                  flightdataid = 7277) group      questionid; 

and result:

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 

which nice , except questionid row not ordered id lowest highest want. made exact same query on flight things appear correctly:

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 

what doing wrong?

if want specific order results, must specify order by, comes after group by in clause order. 2 clauses not mutually exclusive:

select avg(cast(rating numeric(18, 2))) average,      questionid,      count(questionid) count answersrating surveyid in (    select id    surveys    flightdataid = 7277 ) group questionid order questionid; 

your second query returning results in order purely coincidence.


Comments