SQL!统计函数在分组查询与非分组查询的意义的不同?()
admin
2023-07-12 21:22:23
0

相机,尼康SQ,
统计函数就是聚合函数吧?

在分组查询中,
会聚合函数是将数据按分组关键字分组,然后对每一组的函数自变量中的内容进行聚合运算。
在非分组查询中,
聚合函数实际上等于将表中所有记录作为一个组来运算,也就是不分组,如SUM(N)就是对表中所有记录的N段进行求合。
分组查询中
查询字段可以是分组关键字和聚合函数。
非分组查询中
只要有聚合函数出现,查询字段只能是聚合函数(或者说,查询字段只能出现在聚合函数中)。 select 费用区间=(case when 费用=10 and 费用20 then '10-20' when 费用=20 and 费用30 then '20-30' end),count(*) as 个数, sum(费用) as 费用总计
from 表
group by (case when 费用=10 and 费用20 then '10-20' when 费用=20 and 费用30 then '20-30' end)

类似,如果要多个分类,可在case里多加几个 when select 费用/10,sum(费用),count(1) from 表 group by 费用/10 declare @t table (hm varchar(10),fy int)
insert @t values ('23456',12)
insert @t values ('56423',13)
insert @t values ('56321',15)
insert @t values ('89546',25)
insert @t values ('78965',85)
insert @t values ('56789',88)

select bj,count(fy) as sl,sum(fy) as hj from (
select *,substring(cast(fy as varchar(10)),1,1) as bj
from @t) a
group by bj select 号码,
sum(case when 费用 between 10 and 20 then 费用 else 0 end)[10-20],
sum(case when 费用 between 21 and 30 then 费用 else 0 end)[21-30],
sum(case when 费用 between 31 and 40 then 费用 else 0 end)[31-40],
sum(case when 费用 between 41 and 50 then 费用 else 0 end)[41-50],
sum(case when 费用 between 51 and 60 then 费用 else 0 end)[51-60],
sum(case when 费用 between 61 and 70 then 费用 else 0 end)[61-70],
sum(case when 费用 between 71 and 80 then 费用 else 0 end)[71-80]
.....
from 表
group by 号码 用group by就可以解决。
比如表名为test,数据如下
id grade
1 10
1 20
2 40
2 30

现在要求按id分组查询grade的和,可以用如下语句:
select id,sum(grade) as grade from test group by id;
得到的结果是
id grade
1 30
2 70

相关内容