各位用户为了找寻关于在SQL中对同一个字段不同值,进行数据统计操作的资料费劲了很多周折。这里教程网为您整理了关于在SQL中对同一个字段不同值,进行数据统计操作的相关资料,仅供查阅,以下为您介绍关于在SQL中对同一个字段不同值,进行数据统计操作的详细内容
应用场景: 需要根据印章的不同状态,统计不同状态下印章数量。
刚开始百度,确实写搜到了不同的答案,但只能怪自己对sql语法解读不够,还是没写出来,导致写出了下面错误的写法。
? 1 2 3 4 5 6 7 8 9 10select
b.corporateOrgName, b.corporateOrgGuid companyId,
count
(
case
when
bc.ftype
not
in
(1,2)
then
1
else
0
end
) total,
count
(
case
when
bc.ftype
in
(3,4,5)
then
1
else
0
end
) usetotal,
count
(
case
when
bc.ftype = 6
then
1
else
0
end
) saveTotal,
count
(
case
when
bc.ftype = 7
then
1
else
0
end
) returnTotal
from
B_seal_cycle bc
join
B_seal b
on
bc.sealId = b.id
where
b.corporateOrgName
like
'%%'
group
by
b.corporateOrgName,b.corporateOrgGuid
逻辑上通了,可就是怎么都得不到理想的接口,这样写统计的每一个数据都一样呀。改变之后的正确写法
? 1 2 3 4 5 6 7 8 9 10select
b.corporateOrgName, b.corporateOrgGuid companyId,
count
(
case
when
bc.ftype
not
in
(1,2)
then
1
end
) total,
count
(
case
when
bc.ftype
in
(3,4,5)
then
1
end
) usetotal,
count
(
case
when
bc.ftype = 6
then
1
end
) saveTotal,
count
(
case
when
bc.ftype = 7
then
1
end
) returnTotal
from
B_seal_cycle bc
join
B_seal b
on
bc.sealId = b.id
where
b.corporateOrgName
like
'%%'
group
by
b.corporateOrgName,b.corporateOrgGuid
你看出不同之处了嘛? 把else 0 去掉就得到了正确的结果。
遇到的问题
1、 对case when 语法,解读有误。
加了else 之后,总会对结果取 1 或 0.
2、 count函数都会对不管1 或 0 进行统计。
3、 当加了else 0 之后,可以通过sum函数进行统计。
也可以这样写
? 1 2 3 4 5 6 7 8 9 10select
b.corporateOrgName, b.corporateOrgGuid companyId,
sum
(
case
when
bc.ftype
not
in
(1,2)
then
1
else
0
end
) total,
sum
(
case
when
bc.ftype
in
(3,4,5)
then
1
else
0
end
) usetotal,
sum
(
case
when
bc.ftype = 6
then
1
else
0
end
) saveTotal,
sum
(
case
when
bc.ftype = 7
then
1
else
0
end
) returnTotal
from
B_seal_cycle bc
join
B_seal b
on
bc.sealId = b.id
where
b.corporateOrgName
like
'%%'
group
by
b.corporateOrgName,b.corporateOrgGuid
有问题,或者有更好的写法,感谢留言指出。
补充知识:SQL语言中 执行语句 DESC与DESCRIBE有什么区别?
DESCRIBE TABLE 用于列出指定表或视图中的所有列。
DESCRIBE INDEX FOR TABLE 用于列出指定表的所有索引,
所以 DESCRIBE是用来显示数据结构信息的;
而desc是descend ,是用于查询出结果时候对结果进行排序,是降序排序。
DESCRIBE 是 SHOW COLUMNS FROM 的缩写。
DESCRIBE 提供有关一个表的列信息。col_name 可以是一个列名或是一个包含 SQL 通配符字符 “%” 和 “_” 的字符串。没有必要用引号包围字符串。
一、describe命令用于查看特定表的详细设计信息
例如为了查看guestbook表的设计信息,可用:
describe guestbook describe ol_user userid
二、可通过”show comnus”来查看数据库中表的列名
有两种使用方式:
show columns form 表名 from 数据库名
或者:
show columns from 数据库名.表名
三、用describe命令查询具体列的信息
describe guestbook id 就是查询guestbook中id字段的列信息
? 1 2 3{DESCRIBE |
DESC
} tbl_name [col_name | wild]
DESCRIBE 是 SHOW COLUMNS FROM 的缩写。
DESCRIBE 提供有关一个表的列信息。col_name 可以是一个列名或是一个包含 SQL 通配符字符 “%” 和 “_” 的字符串。没有必要用引号包围字符串。
? 1 2 3mysql>
desc
ol_user usernameG
四、判断字段是否存在
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15mysql_connect(
'localhost'
,
'root'
,
'root'
);
mysql_select_db(
'demo'
);
$test = mysql_query(
'Describe cdb_posts first'
);
$test = mysql_fetch_array($test);
$test[0]返回的是该字段的名称,比如我要查询first字段,返回的就是first
如果此字段不存在返回的就是NULL,通过这样可以判断一个字段是否存在
以上这篇在SQL中对同一个字段不同值,进行数据统计操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/taojin12/article/details/102724197