mysql 查询实战3-解答

        对mysql 查询实战3-题目,进行一个解答

11、查询每⽉产品交易与退款情况

        目标:查询每⽉产品交易(交易总额,交易数)与退款情况(退款总额,退款数)

1,先把日期格式化

使用 EXTRACT
SELECT  EXTRACT(YEAR_MONTH FROM t.trans_date) AS months FROM transactions t;
        这个不符合我们常见的年月格式,还是用DATE_FORMAT
使用DATE_FORMAT
SELECT id, product_id, amount, DATE_FORMAT(t.trans_date, '%Y-%m') AS months 
FROM transactions t;

2,统计成功的 ,加个flag标记, 0 成功, 1 失败 

SELECT  product_id, amount AS sum_amount, 
DATE_FORMAT(t.trans_date, '%Y-%m') AS months, 0 AS flag
FROM transactions t WHERE state = 'success' ;

3,统计失败的,加个flag标记, 0 成功, 1 失败

SELECT product_id, SUM(amount) AS sum_amount, 
DATE_FORMAT(r.trans_date, '%Y-%m') AS months, 1 AS flagFROM transactions t, refund r
WHERE t.id = r.trans_id
GROUP BY product_id, months;

4, 拼接到一起 

SELECT  product_id, amount AS sum_amount, 
DATE_FORMAT(t.trans_date, '%Y-%m') AS months, 0 AS flag
FROM transactions t WHERE state = 'success' 
UNION 
SELECT product_id, SUM(amount) AS sum_amount, 
DATE_FORMAT(r.trans_date, '%Y-%m') AS months, 1 AS flagFROM transactions t, refund r
WHERE t.id = r.trans_id
GROUP BY product_id, months;

5,再进行判断统计

 SELECT months, product_id,
SUM(CASE WHEN flag=0 THEN sum_amount ELSE 0 END) AS success_total,
COUNT(CASE WHEN flag=0 THEN 1 ELSE NULL END) AS success_count,
SUM(CASE WHEN flag=1 THEN sum_amount ELSE 0 END) AS fail_total,
COUNT(CASE WHEN flag=1 THEN 1 ELSE NULL END) AS fail_count
FROM(
SELECT  product_id, amount AS sum_amount, 
DATE_FORMAT(t.trans_date, '%Y-%m') AS months , 0 AS flag
FROM transactions t WHERE state = 'success' 
UNION ALL
SELECT product_id, SUM(amount) AS sum_amount, 
DATE_FORMAT(r.trans_date, '%Y-%m') AS months , 1 AS flagFROM transactions t, refund r
WHERE t.id = r.trans_id
GROUP BY product_id, months
) AS tmp GROUP BY product_id, months 
ORDER BY months,product_id;

12、查询活动产品的平均价格

1,关联查询

SELECT * FROM sold AS s,  activity AS a
WHERE s.product_id=a.product_id 
AND s.purchase_date BETWEEN a.start_date AND a.end_date;

2,进行统计: 计算平均值,总价格/总数量

SELECT s.product_id, SUM(s.num*a.price)/SUM(num) AS average_price 
FROM sold AS s,  activity AS a
WHERE s.product_id=a.product_id 
AND s.purchase_date BETWEEN a.start_date AND a.end_date 
GROUP BY a.product_id;

3,保留两位小数  

SELECT s.product_id, ROUND(SUM(s.num*a.price)/SUM(num),2) AS average_price 
FROM sold AS s,  activity AS a
WHERE s.product_id=a.product_id 
AND s.purchase_date BETWEEN a.start_date AND a.end_date 
GROUP BY a.product_id;

13、统计部⻔每⽉收⼊概况

1,先统计一月的情况 

SELECT department_id, 
SUM(CASE MONTH WHEN 'Jan' THEN income ELSE 0 END) Jan_income
FROM department_income
GROUP BY department_id;

2,再统计全年的

SELECT department_id,
SUM(CASE MONTH WHEN 'Jan' THEN income ELSE 0 END) Jan_income,
SUM(CASE MONTH WHEN 'Feb' THEN income ELSE 0 END) Feb_income,
SUM(CASE MONTH WHEN 'Mar' THEN income ELSE 0 END) Mar_income,
SUM(CASE MONTH WHEN 'Apr' THEN income ELSE 0 END) Apr_income,
SUM(CASE MONTH WHEN 'May' THEN income ELSE 0 END) May_income,
SUM(CASE MONTH WHEN 'Jun' THEN income ELSE 0 END) Jun_income,
SUM(CASE MONTH WHEN 'Jul' THEN income ELSE 0 END) Jul_income,
SUM(CASE MONTH WHEN 'Aug' THEN income ELSE 0 END) Aug_income,
SUM(CASE MONTH WHEN 'Sep' THEN income ELSE 0 END) Sep_income,
SUM(CASE MONTH WHEN 'Oct' THEN income ELSE 0 END) Oct_income,
SUM(CASE MONTH WHEN 'Nov' THEN income ELSE 0 END) Nov_income,
SUM(CASE MONTH WHEN 'Dec' THEN income ELSE 0 END) Dec_income
FROM department_income
GROUP BY department_id

3,改成用if的方式:

        IF(expr, vl, v2),如果表达式expr是TRUE(expr > 0 and expr  NULL),则IF()的返回值为v1;否则返回值为v2

SELECT department_id,
SUM(IF(MONTH = 'Jan' , income, 0)) Jan_income,
SUM(IF(MONTH = 'Feb' , income, 0)) Feb_income,
SUM(IF(MONTH = 'Mar' , income, 0)) Mar_income,
SUM(IF(MONTH = 'Apr' , income, 0)) Apr_income,
SUM(IF(MONTH = 'May' , income, 0)) May_income,
SUM(IF(MONTH = 'Jun' , income, 0)) Jun_income,
SUM(IF(MONTH = 'Jul' , income, 0)) Jul_income,
SUM(IF(MONTH = 'Aug' , income, 0)) Aug_income,
SUM(IF(MONTH = 'Sep' , income, 0)) Sep_income,
SUM(IF(MONTH = 'Oct' , income, 0)) Oct_income,
SUM(IF(MONTH = 'Nov' , income, 0)) Nov_income,
SUM(IF(MONTH = 'Dec' , income, 0)) Dec_income
FROM department_income
GROUP BY department_id;

14、统计课程新学员数量

1,找出人员在课程里面一开始的学习时间,即筛选出新学员

SELECT lr.user_id, lr.course_id, MIN(lr.created_at) start_study_date  
FROM learning_records lr
GROUP BY lr.user_id, lr.course_id;

2,加个时间条件,比如180天内容

SELECT * FROM (
SELECT lr.user_id, lr.course_id, MIN(lr.created_at) start_study_date  
FROM learning_records lr
GROUP BY lr.user_id, lr.course_id
) AS temp WHERE DATEDIFF('2020-06-01', start_study_date) <= 180;

3,再进行统计人数

 SELECT course_id, start_study_date, COUNT(user_id) FROM (
SELECT lr.user_id, lr.course_id, MIN(lr.created_at) start_study_date  
FROM learning_records lr
GROUP BY lr.user_id, lr.course_id
) AS temp WHERE DATEDIFF('2020-06-01', start_study_date) <= 180
GROUP BY start_study_date, course_id 
ORDER BY course_id, start_study_date;

15、平均销售额:部⻔与公司对⽐

        目标: 计算每月部门和公司的收入比较

1,日期格式化

SELECT id, sale_id, income, 
DATE_FORMAT(created_at,'%Y-%m') belong_month 
FROM income;
 

2,先计算公司的收入

SELECT  AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income
GROUP BY belong_month;

3,先计算部门的收入,关联人员表  

SELECT sp.department_id, AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income ic, sales_person sp
WHERE ic.sale_id = sp.id
GROUP BY belong_month, sp.department_id;

4,公司表和部门表,根据公司做一个关联查询 

SELECT d.department_id, c.belong_month,
d.avg_income AS department_avg_income, c.avg_income AS company_avg_income FROM (SELECT  AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income
GROUP BY belong_month) AS c, (SELECT sp.department_id, AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income ic, sales_person sp
WHERE ic.sale_id = sp.id
GROUP BY belong_month, sp.department_id) AS d
WHERE c.belong_month = d.belong_month;

5,再加个标记,判断是高,还是低了

-- if只能判断二元的,这边得用case when
SELECT d.department_id, c.belong_month, 
(CASE WHEN d.avg_income > c.avg_income THEN  'higher'
WHEN d.avg_income < c.avg_income THEN 'lower' ELSE 'same' END) AS mark,
d.avg_income AS department_avg_income, c.avg_income AS company_avg_income FROM (SELECT  AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income
GROUP BY belong_month) AS c,
(SELECT sp.department_id, AVG(income) AS avg_income, 
DATE_FORMAT(created_at,'%Y-%m') AS belong_month 
FROM income ic, sales_person sp
WHERE ic.sale_id = sp.id
GROUP BY belong_month, sp.department_id) AS d
WHERE c.belong_month = d.belong_month;

总结:

        在统计后,进行进一步过滤的时候,case when就非常好用了。if只能判断二元的,有限制。case when可以使用多元,可以统计各种情况,再聚合,把多列的,合并成单列数据,数据再进行处理就很方便了

                

        上一篇: 《mysql 查询实战3-题目》

        下一篇: 《mysql 日环比 统计》

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

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

相关文章

200.trie前缀树

Trie树常用于自动补全&#xff0c;拼写检查&#xff0c;单词搜索&#xff0c;高频统计等领域&#xff0c;一般都是这个模板再加个次数 介绍 题解

STM32直接存储器存取DMA

前提知识&#xff1a; 1、STM32F103内部存储器结构以及映射 STM32F103的程序存储器、数据存储器、寄存器和IO端口被组织在同一个4GB的线性地址空间内。数据字节以小端模式存放在存储器中。即低地址中存放的是字数据的低字节&#xff0c;高地址中存放的是字数据的高字节 可访问…

用Python在PDF文档中插入单图像水印和平铺图像水印

PDF文档因其跨平台兼容性和内容保真度成为信息交换的标准载体&#xff0c;为应对版权侵犯、内容篡改以及未经授权的传播等风险&#xff0c;向PDF中插入图片水印成为一种强化文档安全性、彰显所有权及实施访问控制的有效手段。图片水印不仅能以直观的方式标示文档来源、强化版权…

CH58X使用USB HID进行IAP注意事项——笔记

CH58X使用USB HID进行IAP注意事项——笔记 一、背景 基础 单片机使用CH582M&#xff0c;并使用USB HID进行IAP升级。方案 方案1&#xff1a;APPBOOT方案&#xff0c;可以只安装APP就可以运行&#xff0c;APP中后续安装BOOT程序和后面更新也方便。 方案2&#xff1a;经典IAP方…

Windows:web端UI自动化=python+selenium+pycharm框架

本篇写怎么写一个UI自动化代码。mac和Windows是一样的 都是这样写 不过&#xff0c;习惯用Windows了 如果python没有安装可以看我另一篇安装python的教程 先安装python先 下载完python 下载pip 1 安装pip $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py # 下载…

【centso】sqlite3.7.17升级到更新的版本

下载 创建一个工作目录(非必须) mkdir sqlite3_upgrade cd sqlite3_upgrade下载源码包(官网&#xff1a; https://sqlite.org/download.html) wget https://www.sqlite.org/2020/sqlite-autoconf-3320300.tar.gz #或者 wget https://docs.iterdaily.com/sqlite-autoconf-332…

SpringBoot上传文件夹

SpringBoot上传文件夹 SpringBoot上传文件夹 SpringBoot上传文件夹前言前端后端FileControllerFilesUtil 前言 个人开发过程中的经验总结 前端 此处以vue3为例 <template><form submit.prevent"uploadFiles" ref"form"><inputtype"…

Sentinel + Nacos流控规则持久化配置

json参数对映sentinel 规则面板 [{"controlBehavior": 0,"count": 2,"grade": 1,"limitApp": "default","resource": "flow","strategy": 0} ] 第二步&#xff0c;告诉订单服务读取配置&…

Golang | Leetcode Golang题解之第38题外观数列

题目&#xff1a; 题解&#xff1a; func countAndSay(n int) string {prev : "1"for i : 2; i < n; i {cur : &strings.Builder{}for j, start : 0, 0; j < len(prev); start j {for j < len(prev) && prev[j] prev[start] {j}cur.WriteStr…

Ubuntu的终端中启用鼠标左键即为选中复制,右键粘贴的功能

在Ubuntu终端中启用鼠标复制和粘贴的功能需要进行一些设置。 首先&#xff0c;打开终端窗口&#xff0c;在菜单栏中找到“Edit”选项&#xff0c;点击“Profile Preferences”。然后&#xff0c;在“General”选项卡中&#xff0c;勾选“Use custom font”选项&#xff0c;可以…

Excel中将单元格格式改成文本后,为何要双击数字才会改变?

将大批量的数值型数字转换成文本型数字&#xff0c;当然不能一个一个的去双击做转换了。以下说说有哪个可以将数值型数字转换成文本型数字的方法。 一、转换方法 方法1.数据分列功能 选中数据后&#xff0c;点击数据选项卡&#xff0c;分列&#xff0c; 分列向导的第一步和…

Transformer推理性能优化技术很重要的一个就是K V cache,能否通俗分析,可以结合代码?

原文&#xff1a;Transformer推理性能优化技术很重要的一个就是K V cache&#xff0c;能否通俗分析&#xff0c;可以结合代码? - 知乎 为什么要研究KV cache&#xff1f; 设输入序列的长度为 s &#xff0c;输出序列的长度为 n &#xff0c;模型深度为l&#xff0c;维度为h,以…

【Taro3踩坑日记】不存在全局配置文件:C:\Users\TYW\.taro-global-config\index.json

鼠鼠想用Taro做一个完整的移动端和小程序项目&#xff0c;结果出师未捷&#xff0c;就遇到个坑。 taro init myApp之后&#xff0c;直接报错&#xff1a;不存在全局配置文件&#xff1a;C:\Users\TYW.taro-global-config\index.json 经过多方查找&#xff0c;有的说要安装taroj…

设计模式:简单工厂模式(Simple Factory)

设计模式&#xff1a;简单工厂模式&#xff08;Simple Factory&#xff09; 设计模式&#xff1a;简单工厂模式&#xff08;Simple Factory&#xff09;模式动机模式定义模式结构时序图模式实现测试模式分析实例&#xff1a;Qt 控件类优缺点适用环境模式应用 设计模式&#xff…

关基网络战时代,赛宁网安电力网络攻防靶场全面提升电网安全防护力

随着网络空间成为与陆地、海洋、天空、太空同等重要的人类活动新领域&#xff0c;自网络空间向物理电网发起攻击&#xff0c;破坏电力等国家关键基础设施成为当前大国博弈、大规模战争的重要手段和常态进攻形式。同时&#xff0c;新型电力系统建设发展驱动电力系统形态和控制方…

基于Springboot的社区待就业人员信息管理系统(有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的社区待就业人员信息管理系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三…

TaskWeaver使用记录

TaskWeaver使用记录 1. 基本介绍2. 总体结构与流程3. 概念细节3.1 Project3.2 Session3.3 Memory3.4 Conversation3.5 Round3.6 Post3.7 Attachment3.8 Plugin3.9 Executor 4. 代码特点5. 使用过程5.1 api调用5.2 本地模型使用5.3 添加插件 6. 存在的问题与使用体验6.1 判别模型…

Docker搭建nano-wallet

nano-wallet 是一个Docker镜像&#xff0c;用于运行Nano cryptocurrency的钱包服务。Nano是一种去中心化的数字货币&#xff0c;使用了区块链技术来提供快速且无交易费用的支付服务。使用该Docker镜像可以方便地在各种环境中部署Nano钱包服务&#xff0c;便于执行交易、查看账户…

笔记本电脑坏了硬盘数据会丢失吗 笔记本电脑坏了如何取出硬盘的资料 数据恢复软件

笔记本电脑对我们真的非常重要了&#xff0c;是实现无纸化办公和学习的重要工具&#xff0c;但是如果笔记本电脑坏了我们存储在电脑里的资料该怎么办&#xff1f;笔记本电脑坏了硬盘数据会丢失吗&#xff1f;相信有许多朋友都会有这样的担忧。本文今天就为大家解决笔记本电脑坏…

【银角大王———Django学习DAY0——基础准备】

银角大王——Django学习前情提要 &#xff08;1&#xff09;在pycharm中下载Flask&#xff08;2&#xff09;使用Flask&#xff08;3&#xff09;下载BootStrap框架&#xff08;4&#xff09; 使用BootStrap框架 &#xff08;1&#xff09;在pycharm中下载Flask 在设置——项目…