问题描述
- 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]))
解决方案二:
恩。是个办法。但是需要建表。而且维护不易。从论坛看到这么个方法。
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
解决方案三:
value可以是null的?不然不可能没有4 5啊,贴出你原始数据看看
解决方案四:
value是可以不添的。也就是说。用户选择了type是1 2 3 的项。没选择4和5的项。那么数据库里就不存在type是4和5的数据了。
解决方案五:
SqlServer 根据字段分类汇总信息
解决方案六:
你把所有的value值都+1 这样就没有0了,最少就是1,查询出来把结果-1不就完了,简单明了
时间: 2024-09-17 04:34:13