赞
踩
(1)sum()函数里面的参数是列名的时候,是计算列名的值的相加,而不是有值项的总数。
(2)sum(条件表达式),如果记录满足条件表达式就加1,统计满足条件的行数
(1)COUNT()函数里面的参数是列名的的时候,那么会计算有值项的次数。(NULL 不计入, 但是’'值计入)
(2)COUNT(*)可以计算出行数,包括null
(3)COUNT(1)也可以计算出行数,1在这里代表一行
(4)COUNT(column_name)对特定的列的值具有的行数进行计算,不包含NULL值
(5)COUNT(条件表达式),不管记录是否满足条件表达式,只要非NULL就加1
经常会用两种查询语句有两种:第1个正确,第2个错误
1.select name,sum(score < 60) ,avg(score) from result group by name having sum(score<60) >=2;
2.select name ,count((score<60)!=0) as a,avg(score) from result group by name having a >=2;
SELECT count(*) FROM 表名 WHERE 条件 // 这样查出来的是总记录条
SELECT count(*) FROM 表名 WHERE 条件 GROUP BY id //这样统计的会是每组的记录条数.
select count() from(SELECT count() FROM 表名 WHERE 条件 GROUP BY id ) a ;
SELECT count() FROM (SELECT COUNT() FROM
papa_stadium_goods_storage_record
WHEREc_time
>=1474560000 andc_time
<1476201600 group byrecord_type
) a
注意:子查询方式,MySQL中子结果集必须使用别名,而Oracle中不需要特意加别名!
DROP TABLE IF EXISTS `tongji`;
create table tongji(
tyear varchar(255),
tmonth int,
amount double
)Engine=Innodb default charset=utf8;
insert into tongji values('2011',1,1.1),('2011',2,1.2),('2011',3,1.3),('2011',4,1.4),('2012',1,2.1),('2012',2,2.2)
,('2012',3,2.3),('2012',4,2.4);
select * from tongji;
SELECT t.tyear ,
sum(if(t.tmonth=1,t.amount,null )) as 'm1' ,
sum(if(t.tmonth=2,t.amount,null )) as 'm2' ,
sum(if(t.tmonth=3,t.amount,null )) as 'm3' ,
sum(if(t.tmonth=4,t.amount,null )) as 'm4'
FROM tongji t GROUP BY (t.tyear);
null 就是if 判断结果为else的时候返回 null。 语法格式是这样的: if(条件, 为true, 为false)
核心知识点:如果这里去掉sum()函数,查询的记录,会是下面这种结果,这是因为group语句分组的时候,存在一条对应多条记录的时候,只会显示一条,对应的多条会被覆盖,所以会出现这种结果
SELECT distribution_order_username as distributionOrderUsername, sum(if(a.chat_status=1,count,0)) as 'dtgwx' , sum(if(a.chat_status=2,count,0)) as 'khjj' , sum(if(a.chat_status=3,count,0)) as 'wjt' , sum(if(a.chat_status=4,count,0)) as 'dhf', sum(if(a.chat_status=5,count,0)) as 'wlx', sum(if(a.chat_status=6,count,0)) as 'yjwx', sum(if(a.chat_status,count,0)) as 'total' FROM SELECT distribution_order_username as distributionOrderUsername, sum(if(a.buyctiyid=440100,count,0)) as 'gz', sum(if(a.buyctiyid=440300,count,0)) as 'sz' , sum(if(a.buyctiyid=441900,count,0)) as 'dg' , sum(if(a.buyctiyid in (440100,440300,441900),count,0)) as 'total' FROM
select DATE_FORMAT(created_time,'%Y-%m-%d') as '日期',
sum(if(product='毛巾',price,0)) as '毛巾',
sum(if(product='枕头',price,0)) as '枕头'
from trade
GROUP BY DATE_FORMAT(created_time,'%Y-%m-%d');
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。