板凳-------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
英文地址,請注明出處:http://en.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;之…