SQL 分组统计,再合并组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 分组统计,再合并组相关的知识,希望对你有一定的参考价值。

SQL运行结果如下:
组名 产品 数量
A aa 1
B bb 2
C cc 3
A1 cc 3
B1 cc 3
把组名为 A 和 A1 ,B 和 B1 的数量合并,想要这样的结果
组名 产品 数量
A aa 4
B bb 5
C cc 3

参考技术A select
ta.deptname,
count(ta.deptname)
as
personcount,
sum(ta.status1)
as
status1,
sum(ta.status2)
as
status2,
sum(ta.status3)
as
status3,
sum(ta.status4)
as
status4
from
(select
deptname,
case
status
when
'状态1'
then
1
else
0
end
as
status1,
case
status
when
'状态2'
then
1
else
0
end
as
status2,
case
status
when
'状态3'
then
1
else
0
end
as
status3,
case
status
when
'状态4'
then
1
else
0
end
as
status4
from
tablename
where
datepart(y,
date)=2011
and
datepart(m,
date)=1)
ta
group
by
ta.deptname
月份需要加上年份一起判断,
合计不能从这条语句中得到,可以通过另外一条语句或者通过程序中对数据分析得到,不知道你前台用什么开发的,是不是有控件可以直接生成.
select
count(*)
as
recordcount,
sum(tb.status1)
as
status1,
sum(tb.status2)
as
status2,
sum(tb.status3)
as
status3,
sum(tb.status4)
as
status4
from
(select
ta.deptname,
count(ta.deptname)
as
personcount,
sum(ta.status1)
as
status1,
sum(ta.status2)
as
status2,
sum(ta.status3)
as
status3,
sum(ta.status4)
as
status4
from
(select
deptname,
case
status
when
'状态1'
then
1
else
0
end
as
status1,
case
status
when
'状态2'
then
1
else
0
end
as
status2,
case
status
when
'状态3'
then
1
else
0
end
as
status3,
case
status
when
'状态4'
then
1
else
0
end
as
status4
from
tablename
where
datepart(y,
date)=2011
and
datepart(m,
date)=1)
ta
group
by
ta.deptname)
tb
这条语句可以得到合计值
参考技术B select 组名2 as 组名, 产品2 as 产品,sum(数量) as 数量
from
(select case when 组名 = 'A1' then 'A' when 组名 = 'B1' then 'B' else 组名 end as 组名2,case when 组名 = 'A1' then 'aa' when 组名 = 'B1' then 'bb' else 产品 end as 产品2 ,数量
from 表
) tb
group by 组名2, 产品2本回答被提问者采纳
参考技术C select left(组名,1) as new_组名,min(产品) as new_产品,sum(数量) from 表 group by left(组名,1) order by new_组名 参考技术D 给你句简单也是速度最快的:
select left(组名,1),min(产品),sum(数量)
from a
group by left(组名,1)
第5个回答  2010-06-03 select substring(组名,1,1) as 组名,产品,sum(数量) as 数量 from 表 group by substring(组名,1,1);

以上是关于SQL 分组统计,再合并组的主要内容,如果未能解决你的问题,请参考以下文章

pandas分组与聚合

Pandas分组与聚合

Stream Collectors.groupingBy的四种用法 解决分组统计(计数求和平均数等)范围统计分组合并分组结果自定义映射等问题

SQL分组查询

sql语句 按一列分组 然后再按别一列组内排序?

第十三节 pandas分组和分组统计以及多数据源合并