板凳-------Mysql cookbook学习 (十--9)

8.15 基于日期的摘要 Monday, June 23, 2025

mysql> use cookbook
Database changed
mysql> select trav_date,-> count(*) as 'number of drivers', sum(miles) as 'miles logged'-> from driver_log group by trav_date;
+------------+-------------------+--------------+
| trav_date  | number of drivers | miles logged |
+------------+-------------------+--------------+
| 2014-07-30 |                 2 |          355 |
| 2014-07-29 |                 3 |          822 |
| 2014-07-27 |                 1 |           96 |
| 2014-07-26 |                 1 |          115 |
| 2014-08-02 |                 2 |          581 |
| 2014-08-01 |                 1 |          197 |
+------------+-------------------+--------------+
6 rows in set (0.01 sec)mysql> select hour(t ) as hour,-> count(*) as 'number of messages',-> sum(size) as 'number of bytes sent'-> from mail-> group by hour;
+------+--------------------+----------------------+
| hour | number of messages | number of bytes sent |
+------+--------------------+----------------------+
|   10 |                  2 |              1056806 |
|   12 |                  2 |               195798 |
|   15 |                  1 |                 1048 |
|   13 |                  1 |                  271 |
|    9 |                  2 |                 2904 |
|   11 |                  1 |                 5781 |
|   14 |                  1 |                98151 |
|   17 |                  2 |              2398338 |
|    7 |                  1 |                 3824 |
|    8 |                  1 |                  978 |
|   23 |                  1 |                10294 |
|   22 |                  1 |                23992 |
+------+--------------------+----------------------+
12 rows in set (0.01 sec)mysql> select dayofweek(t) as weekday,-> count(*) as 'number of messages',-> sum(size) as 'number of bytes sent'-> from mail-> group by weekday;
+---------+--------------------+----------------------+
| weekday | number of messages | number of bytes sent |
+---------+--------------------+----------------------+
|       5 |                  1 |                58274 |
|       6 |                  3 |               219965 |
|       7 |                  1 |                  271 |
|       1 |                  4 |              2500705 |
|       2 |                  4 |              1007190 |
|       3 |                  2 |                10907 |
|       4 |                  1 |                  873 |
+---------+--------------------+----------------------+
7 rows in set (0.00 sec)mysql> SELECT dayname(t) as weekday,->        count(*) as 'number of messages',->        sum(size) as 'number of bytes sent'-> FROM mail-> GROUP BY dayname(t), dayofweek(t);
+-----------+--------------------+----------------------+
| weekday   | number of messages | number of bytes sent |
+-----------+--------------------+----------------------+
| Thursday  |                  1 |                58274 |
| Friday    |                  3 |               219965 |
| Saturday  |                  1 |                  271 |
| Sunday    |                  4 |              2500705 |
| Monday    |                  4 |              1007190 |
| Tuesday   |                  2 |                10907 |
| Wednesday |                  1 |                  873 |
+-----------+--------------------+----------------------+
7 rows in set (0.00 sec)

8.16 同时使用每一组的摘要和全体的摘要

mysql> select @total := sum(miles) as 'total miles' from driver_log;
+-------------+
| total miles |
+-------------+
|        2166 |
+-------------+
1 row in set, 1 warning (0.00 sec)mysql> select name,-> sum(miles) as 'miles/driver',-> (sum(miles)* 100)/@total as 'percent of total miles'-> from driver_log group by name;
+-------+--------------+------------------------+
| name  | miles/driver | percent of total miles |
+-------+--------------+------------------------+
| Ben   |          362 |                16.7128 |
| Suzi  |          893 |                41.2281 |
| Henry |          911 |                42.0591 |
+-------+--------------+------------------------+
3 rows in set (0.00 sec)mysql> select name,-> sum(miles) as 'miles/driver',-> (sum(miles)* 100)/(select sum(miles) from driver_log)-> as 'percent of total miles'-> from driver_log group by name;
+-------+--------------+------------------------+
| name  | miles/driver | percent of total miles |
+-------+--------------+------------------------+
| Ben   |          362 |                16.7128 |
| Suzi  |          893 |                41.2281 |
| Henry |          911 |                42.0591 |
+-------+--------------+------------------------+
3 rows in set (0.00 sec)mysql> select name, avg(miles) as driver_avg from driver_log-> group by name-> having driver_avg < (select avg(miles) from driver_log);
+-------+------------+
| name  | driver_avg |
+-------+------------+
| Ben   |   120.6667 |
| Henry |   182.2000 |
+-------+------------+
2 rows in set (0.00 sec)mysql> select name, sum(miles) as 'miles/driver'-> from driver_log group by name with rollup;
+-------+--------------+
| name  | miles/driver |
+-------+--------------+
| Ben   |          362 |
| Henry |          911 |
| Suzi  |          893 |
| NULL  |         2166 |
+-------+--------------+
4 rows in set (0.00 sec)mysql> select name, avg(miles) as driver_avg from driver_log-> group by name with rollup;
+-------+------------+
| name  | driver_avg |
+-------+------------+
| Ben   |   120.6667 |
| Henry |   182.2000 |
| Suzi  |   446.5000 |
| NULL  |   216.6000 |
+-------+------------+
4 rows in set (0.00 sec)mysql> select srcuser, dstuser, count(*)-> from mail group by srcuser, dstuser;
+---------+---------+----------+
| srcuser | dstuser | count(*) |
+---------+---------+----------+
| barb    | tricia  |        2 |
| tricia  | gene    |        1 |
| phil    | phil    |        2 |
| gene    | barb    |        2 |
| phil    | tricia  |        2 |
| barb    | barb    |        1 |
| tricia  | phil    |        1 |
| gene    | gene    |        3 |
| gene    | tricia  |        1 |
| phil    | barb    |        1 |
+---------+---------+----------+
10 rows in set (0.00 sec)mysql> select srcuser, dstuser, count(*)-> from mail group by srcuser, dstuser with rollup;
+---------+---------+----------+
| srcuser | dstuser | count(*) |
+---------+---------+----------+
| barb    | barb    |        1 |
| barb    | tricia  |        2 |
| barb    | NULL    |        3 |
| gene    | barb    |        2 |
| gene    | gene    |        3 |
| gene    | tricia  |        1 |
| gene    | NULL    |        6 |
| phil    | barb    |        1 |
| phil    | phil    |        2 |
| phil    | tricia  |        2 |
| phil    | NULL    |        5 |
| tricia  | gene    |        1 |
| tricia  | phil    |        1 |
| tricia  | NULL    |        2 |
| NULL    | NULL    |       16 |
+---------+---------+----------+
15 rows in set (0.00 sec)

8.17 生成包括摘要和列表的报告

import os
import configparser
import mysql.connector
from mysql.connector import Error
import loggingdef query_mail_data():# Method: Read from config file (recommended)config_path = 'D:/sql/Mysql_learning/config.ini'# Initialize logginglogging.basicConfig(level=logging.INFO)# Read configurationconfig = configparser.ConfigParser()if os.path.exists(config_path):config.read(config_path)try:db_config = {'host': config.get('database', 'host', fallback='localhost'),'user': config.get('database', 'user'),'password': config.get('database', 'password'),'database': config.get('database', 'database', fallback='cookbook')}except configparser.NoSectionError:logging.error("配置文件缺少 [database] 部分")raiseexcept configparser.NoOptionError as e:logging.error(f"配置选项缺失: {e}")raiseelse:logging.error(f"配置文件 {config_path} 不存在")raise FileNotFoundError(f"配置文件 {config_path} 不存在")connection = Nonecursor = Nonetry:# Establish database connectionconnection = mysql.connector.connect(**db_config)if connection.is_connected():cursor = connection.cursor(dictionary=True)# First query: get summary data per drivername_map = {}cursor.execute("""SELECT name, COUNT(name) as days, SUM(miles) as total_milesFROM driver_log GROUP BY name""")for row in cursor:name_map[row['name']] = (row['days'], row['total_miles'])# Second query: get detailed trips per drivercursor.execute("""SELECT name, trav_date, milesFROM driver_log ORDER BY name, trav_date""")current_name = ""for row in cursor:if current_name != row['name']:print(f"Name: {row['name']}; days on road: {name_map[row['name']][0]}; miles driven: {name_map[row['name']][1]}")current_name = row['name']print(f"Date: {row['trav_date']}, trip length: {row['miles']}")except Error as e:logging.error(f"数据库错误: {e}")raisefinally:# Clean up resourcesif cursor:cursor.close()if connection and connection.is_connected():connection.close()# Call the function
query_mail_data()
Name: Ben; days on road: 3; miles driven: 362
Date: 2014-07-29, trip length: 131
Date: 2014-07-30, trip length: 152
Date: 2014-08-02, trip length: 79
Name: Henry; days on road: 5; miles driven: 911
Date: 2014-07-26, trip length: 115
Date: 2014-07-27, trip length: 96
Date: 2014-07-29, trip length: 300
Date: 2014-07-30, trip length: 203
Date: 2014-08-01, trip length: 197
Name: Suzi; days on road: 2; miles driven: 893
Date: 2014-07-29, trip length: 391
Date: 2014-08-02, trip length: 502

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/88674.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/88674.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

redis的scan使用详解,结合spring使用详解

Redis的SCAN命令是一种非阻塞的迭代器&#xff0c;用于逐步遍历数据库中的键&#xff0c;特别适合处理大数据库。下面详细介绍其使用方法及在Spring框架中的集成方式。 SCAN命令基础 SCAN命令的基本语法&#xff1a; SCAN cursor [MATCH pattern] [COUNT count]cursor&#…

Go 语言并发模式实践

在 Go 语言并发编程中&#xff0c;合理的并发模式能显著提升程序的可维护性和性能。本文将深入解析三种典型的并发模式实现&#xff0c;通过具体案例展示如何优雅地管理任务生命周期、资源池和工作 goroutine 池。 一、runner 模式&#xff1a;任务生命周期管理 在定时任务、…

【Java 开发日记】你会不会使用 SpringBoot 整合 Flowable 快速实现工作流呢?

目录 1、流程引擎介绍 2、创建项目 3、画流程图 4、开发接口 4.1 Java 类梳理 ProcessDefinition ProcessInstance Activity Execution Task 4.2 查看流程图 4.3 开启一个流程 4.4 将请求提交给组长 4.5 组长审批 4.6 经理审批 4.7 拒绝流程 1、流程引擎介绍 …

面试150 分发糖果

思路 联想贪心算法&#xff0c;遍历两次数组&#xff0c;一次是从左到右遍历&#xff0c;只比较右边孩子评分比左边打的情况。第二次从右到左遍历&#xff0c;只比较左边孩子评分比右边大的情况。最后求和即可 class Solution:def candy(self, ratings: List[int]) -> int…

csp基础之进制转换器

一、进制转换要明白的基础知识。。。 1、什么是进制&#xff1f; 进制也就是进位计数制&#xff0c;是人为定义的带进位的计数方法。对于任何一种进制 X 进制&#xff0c;就表示每一位置上的数运算时都是逢 X 进一位。十进制是逢十进一&#xff0c;十六进制是逢十六进一&#…

Zephyr OS蓝牙广播(Advertising)功能实现

目录 概述 1 Advertising功能介绍 1.1 实现原理 1.2 广播类型 1.3 广播数据格式 1.4 优化建议 1.5 常见问题和解决方法 2 Nordic 蓝牙广播&#xff08;Advertising&#xff09;功能实现 2.1 环境准备与SDK基础 2.2 广播功能实现 2.3 广播优化与最佳实践 3 实际应用案例…

服务器不支持PUT,DELETE 的解决方案

nginx 的更改&#xff1a; set $method $request_method; if ($http_X_HTTP_Method_Override ~* PUT|DELETE) { set $method $http_X_HTTP_Method_Override; } proxy_method $method; axios 的更改&#xff1a; const method config.me…

从0开始学习计算机视觉--Day04--线性分类

从宏观来看&#xff0c;卷积网络可以看做是由一个个不同的神经网络组件组合而成&#xff0c;就像积木一样通过不同类型的组件搭建形成&#xff0c;其中线性分类器是一个很重要的组件&#xff0c;在很多卷积网络中都有用到&#xff0c;所以了解清楚它的工作原理对我们后续的学习…

基于ComfyUI与Wan2.1模型的本地化视频生成环境搭建指南

文章目录 前言1.软件准备1.1 ComfyUI1.2 文本编码器1.3 VAE1.4 视频生成模型2.整合配置3. 本地运行测试4. 公网使用Wan2.1模型生成视频4.1 创建远程连接公网地址5. 固定远程访问公网地址总结前言 各位小伙伴们,今天我们将为您展示一套创新的人工智能应用方案!本次教程将指导…

Vue 2 项目中内嵌 md 文件

推荐方案&#xff1a;raw-loader marked 解析 Markdown 第一步&#xff1a;安装依赖 npm install marked --save npm install raw-loader --save-dev第二步&#xff1a;配置 webpack 支持 .md 文件 打开 vue.config.js 或 webpack.config.js&#xff0c;添加以下配置&#…

Spring AI初识及简单使用,快速上手。

Spring AI简介 在当今这样一个快速发展的技术时代&#xff0c;人工智能&#xff08;AI&#xff09;已经成为各行各业的一种标配。而作为一款主流的Java应用开发框架Spring&#xff0c;肯定会紧跟时代的潮流&#xff0c;所以&#xff0c;推出了Spring AI框架。 官网描述&#…

Flask中的render_template与make_response:生动解析与深度对比

文章目录 Flask中的render_template与make_response&#xff1a;生动解析与深度对比一、&#x1f31f; 核心概念速览二、&#xfffd; render_template - 网页内容的主厨特点与内部机制适用场景高级用法示例 三、&#x1f381; make_response - 响应的包装专家核心功能解析适用…

WordPress目录说明

在WordPress建站过程中&#xff0c;理解服务器目录结构是非常重要的。以下是一个基础的WordPress服务器目录指南&#xff1a; /wp-admin/ &#xff1a;这个目录包含了WordPress网站的所有管理功能&#xff0c;包括用于处理网站后台的所有PHP文件。 /wp-includes/ &#xff1a;…

HTTP面试题——缓存技术

目录 HTTP缓存技术有哪些&#xff1f; 什么是强制缓存&#xff1f; 什么是协商缓存&#xff1f; HTTP缓存技术有哪些&#xff1f; 对于一些具有重复性的HTTP请求&#xff0c;比如每次请求得到的数据都是一样的&#xff0c;我们可以把这对 请求-响应的数据都缓存在本地&#x…

virtual box 不能分配 USB设备 IFX DAS JDS TriBoard TC2X5 V2.0 [0700] 到虚拟电脑 win10

VirtualBox: Failed to attach the USB device to the virtual machine – Bytefreaks.net ISSUE&#xff1a; virtual box 不能分配 USB设备 IFX DAS JDS TriBoard TC2X5 V2.0 [0700] 到虚拟电脑 win10. USB device IFX DAS JDS TriBoard TC2X5 V2.0 with UUID {91680aeb-e1…

Deepoc大模型重构核工业智能基座:混合增强架构与安全增强决策技术​

面向复杂系统的高可靠AI赋能体系构建 Deepoc大模型通过多维度技术突破&#xff0c;显著提升核工业知识处理与决策可靠性。经核能行业验证&#xff0c;其生成内容可验证性提升68%&#xff0c;关键参数失真率<0.3%&#xff0c;形成覆盖核能全链条的定制化方案&#xff0c;使企…

第12章:冰箱里的CT扫描仪——计算机视觉如何洞穿食材的“生命密码“

第11章:冰箱里的CT扫描仪——计算机视觉如何成为食材健康的"超级诊断官" “糟了!冰箱里草莓长出了白色绒毛,鸡胸肉渗出了可疑的粉红色液体!” 这揭示了厨房生存的更基本挑战:如何像经验丰富的主厨一样,一眼洞穿食材的健康密码? 本章将揭示计算机视觉技术如何赋…

虚幻基础:窗口——重定向

能帮到你的话&#xff0c;就给个赞吧 &#x1f618; 文章目录 重定向&#xff1a;给骨架添加兼容骨架。使得不同模型间复用动画资源 重定向&#xff1a;给骨架添加兼容骨架。使得不同模型间复用动画资源

CSS 逐帧动画

CSS 逐帧动画实现指南 逐帧动画(frame-by-frame animation)是一种通过快速连续显示一系列静态图像来创造运动效果的技术。以下是使用CSS实现逐帧动画的几种方法。 1. 使用 steps() 计时函数 这是实现逐帧动画最常用的方法&#xff0c;通过animation-timing-function的steps(…

高版本IDEA如何开发低版本jdk项目

问题描述 我这个人比较喜欢新的东西&#xff0c;比如使用idea的时候&#xff0c;我就喜欢最新版本。 但是有个问题&#xff0c;最新版本的idea好像不支持jdk1.6&#xff0c;导致我无法去用新版本idea开发项目。 直到有一天&#xff0c;idea给了我一个提示如下&#xff0c;之…