如何使用SQL语句,实现多条件分组统计

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用SQL语句,实现多条件分组统计相关的知识,希望对你有一定的参考价值。

搂主的
SQL
语句,有2点问题
其一.
ACCESS
不支持
CASE
WHEN
要使用
IIF
函数来替换
语法
IIf(expr,
truepart,
falsepart)
IIf
函数的语法包含以下参数
(参数:为操作、事件、方法、属性、函数或过程提供信息的值。):
参数
说明
expr
必选。要计算的表达式。
truepart
必选。expr

True
时返回的值或表达式。
falsepart
必选。expr

False
时返回的值或表达式。
其二.
count
使用的不正确,
应该修改为
sum
select
型号,count(
...
)
as
未报废数量
最后的SQL,
尝试修改为:
select
型号,
sum
(
iif
(
是否报废='否'
,
型号
,
0
)
)
as
未报废数量,
sum(
iif
(
是否借出='是',
型号,
0
)
)
as
已借出数量
from
a
group
by
型号
看看能否获得正确结果么?
参考技术A with
t
as
(
select
'a1'
as
"型号"
,'是'
as
"是否报废",''
as
"是否借出"
from
dual
union
all
select
'a1'
as
"型号"
,'否'
as
"是否报废",'是'
as
"是否借出"
from
dual
union
all
select
'a1'
as
"型号"
,'否'
as
"是否报废",''
as
"是否借出"
from
dual
union
all
select
'b1'
as
"型号"
,'是'
as
"是否报废",''
as
"是否借出"
from
dual
union
all
select
'b1'
as
"型号"
,'是'
as
"是否报废",''
as
"是否借出"
from
dual
union
all
select
'b1'
as
"型号"
,'否'
as
"是否报废",''
as
"是否借出"
from
dual
union
all
select
'c1'
as
"型号"
,'否'
as
"是否报废",'是'
as
"是否借出"
from
dual
union
all
select
'c1'
as
"型号"
,'否'
as
"是否报废",'是'
as
"是否借出"
from
dual
union
all
select
'c1'
as
"型号"
,'否'
as
"是否报废",''
as
"是否借出"
from
dual
)
select
"型号",
count(case
when
"是否报废"
=
'否'
then
"是否报废"
end
)
as
"未报废数量",
count(case
when
"是否借出"
=
'是'
then
"是否借出"
end
)
as
"已借出数量"
from
t
group
by
"型号"
order
by
"型号"
虽然在ORACLE中实现的
但是SQL语句简单修改就可以使用了
参考技术B 用分组,组内计数就可以了,意思就是根据字段a的取值进行分组,相同的为一组,在用count进行组内计数select
a,count(*)from
agroup
by
a

以上是关于如何使用SQL语句,实现多条件分组统计的主要内容,如果未能解决你的问题,请参考以下文章

COUNT分组条件去重的sql统计语句示例(mysql)

mysql 分组之后如何统计记录条数, gourp by 之后的 count

mysql 统计分组之后统计录数条数

08章 分组查询子查询原生SQL

SQL查询语句.GroupBy分组

MySQL 分组之后如何统计记录条数 gourp by 之后的 count()