sql server查询结果连续的问题。

有两个字段value和type,type是int类型。固定1,2,3,4,5。查询数据时按type分组。
具体语句为:
select avg(value) from [table] group by type

得到的结果是
value type
2 1
2 2
4 3

期望的结果是
value type
2 1
2 2
4 3
0 4
0 5

也就是没有的用0来填充。

 再定义一个表,叫t1,两个字段:value type,数据
0 1
0 2
...
0 5

查询
(select avg(value) as value from [table] group by type) union (select * from t1 where t1.type not in (select type from [table]))

value可以是null的?不然不可能没有4 5啊,贴出你原始数据看看

value是可以不添的。也就是说。用户选择了type是1 2 3 的项。没选择4和5的项。那么数据库里就不存在type是4和5的数据了。

恩。是个办法。但是需要建表。而且维护不易。从论坛看到这么个方法。

 select a.number,ISNULL(b.value,0) from 
(select number from master..spt_values
where type='p' and number between 1 and 5) a

left join 

(SELECT  AVG(value) AS value, type
FROM         [table]

GROUP BY type ) b
on a.number = b.type

SqlServer 根据字段分类汇总信息

你把所有的value值都+1 这样就没有0了,最少就是1,查询出来把结果-1不就完了,简单明了