时间:2021-07-01 10:21:17 帮助过:6人阅读
今天需要这样一句sql:先用group by进行分组,然后利用聚合函数count 或者sum进行计算,并显示其它的辅助信息。在MySQL环境中,我
今天需要这样一句sql:先用group by进行分组,然后利用聚合函数count 或者sum进行计算,并显示其它的辅助信息。
在MySQL环境中,我模拟如下环境:
CREATE TABLE `room` (
`rid` varchar(5) default NULL,
`rname` varchar(5) default NULL,
`pid` int(11) default NULL,
`seq` int(11) NOT NULL auto_increment,
PRIMARY KEY (`seq`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
房间表,seq房间入住序号(主键),rname为房间名,这里不考虑第三范式
情景:人住房间,
统计某个房间某个人住的次数
用户表,客人的信息
CREATE TABLE `user1` (
`ID` int(11) NOT NULL auto_increment,
`USERNAME` varchar(50) default '',
`PASSWORD` varchar(50) default '',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk
Mysql中语句如下:
select count(u.username),,r.rname,r.rid,r.pid
from room r,user1 u
where r.pid=u.id
group by r.rid,r.pid
这里r.rname并没有出现在group by子句、聚合函数中,但是MYSQL中仍然能够执行、列出数据。
但是,在Oracle中,却不能!!!!
Oracle环境中:
/*
--显示:Ora-00979 not a ORDER BY expression
--因为: order by 后边的c.channel_code不在ORDER BY子句中
select count(c.channel_name),m.media_name
from channel c,media m
where c.media_code = m.media_code
group by c.media_code,m.media_name
order by c.channel_code
--显示:Ora-00979 not a GROUP BY expression
--因为:group by 或者聚合函数中没有包含c.channel_name
select count(c.channel_name),m.media_name,c.channel_name
from channel c,media m
where c.media_code = m.media_code
group by c.media_code,m.media_name
*/
--通过:
select count(c.channel_name),m.media_name
from channel c,media m
where c.media_code = m.media_code
group by m.media_name
--正常
select count(c.channel_name),m.media_name
from channel c,media m
where c.media_code = m.media_code
group by c.media_code,m.media_name
--正常
select count(c.channel_code),m.media_name
from channel c,media m
where c.media_code = m.media_code
group by c.media_code,m.media_name