SQL增强
需求 : 统计今天每个小时分别有多个pv
分组字段 : 天 小时
天恰好就是分区字段 通过分区字段即可过滤出
真正的分子字段就一个 hour
编写sql的思路 :
- 首先明确开始关键字 , 如
select- 其次我们先跳过需要查询的东西 , 去关注查询的来源 , 即
from, 若后面接的是一个真实存在的表 , 则直接写 , 若不是真实存在的 , 也是通过另外方式获取的 , 比如也是通过查询获得的==>即子查询- 再关注
where(分组前)过滤的条件- 在关注分组
group byhaving(分组后)的过滤order by...- sql基本功 写还是读 寻找到
sql 关键字from table(真实表 来自于子查询返回的结果)select ... from t_user(...) t where(条件...) group by having order by 如找出北京 男女 余额宝不为空的人数并降序排序 select count(*) as nums from t_user t where city="beijing" group by t.sex having t.yuebao is not null order by nums desc; --注意每个关键字的意义 , 尤其是where having --若表来自于另外的查询 --即子查询嵌套查询 select count(*) as nums from { select a.*,b.* from b join c on b.id=c.id } t where city="beijing" group by t.sex having t.yuebao is not null order by nums desc; --form后面的表可能不存在,而是来自于另外一个查询语句返回的结果 嵌套子查询(先里后外)
回到上面的需求 :
select
count(*) as pvs
from ods_weblog_detail t
where datestr='20130918'
group by t.hour
--获取到每小时的pvs
--加上小时标记
select
t.hour,count(*) as pvs
from ods_weblog_detail t
where datestr='20130918'
group by t.hour;
--输出结果为小时对应的pvs数
--若我们想知道是哪天的呢???
select
t.day,t.hour,count(*) as pvs
from ods_weblog_detail t
where datestr='20130918'
group by t.hour;
报错 : Invalid column reference 'day'
group by的语法限制
在有group by的语句中,出现在select后面的字段要么是分组的字段要么是被聚合函数包围的字段。

解决方案: 在前一个分组的基础上继续分组
解决:
select
t.day,t.hour,count(*) as pvs
from ods_weblog_detail t
where datestr='20130918'
group by t.day,t.hour;
--结果类型如下
t.day,t.hour t.hour
18:6 6
18:7 7
18:6 6
--加上月份
select
t.month,t.day,t.hour,count(*) as pvs
from ods_weblog_detail t
where datestr='20130918'
group by t.month,t.day,t.hour;
问题 : 多分组字段中的顺序会不会影响最终结果==>不会

由上图可以得出多分组字段的顺序不影响最终的结果 , 只影响执行的顺序
本文探讨如何增强SQL以实现统计每天每小时的页面访问量(PV)。内容包括理解查询来源、设置过滤条件、使用分组以及解决在GROUP BY语句中遇到的语法限制问题。实践证明,在多分组字段中,顺序不影响最终结果,但影响执行顺序。

1169

被折叠的 条评论
为什么被折叠?



