前述
知识点学习:
- SQL 日期函数 day() 、month()、year() 各种使用方法
- mysql 两个字符年月拼接
题目描述
leetcode题目:1193. 每月交易 I
思路
先按照年月排,再按照country排列
日期拼接相关的函数
year()
: 截取年份;month()
:截取月份;day()
: 截取日期;concat()
:字符串拼接;LPAD()
: 在月份前补齐0,确保月份是两位数。'-'
:分隔符,举例:‘2018-12’ 中的 ‘-’DATE_FORMAT()
:格式化日期。DATE_FORMAT('2018-12-23', '%Y-%m')
注意:对比区分
count(if(state='approved', 1, null))
sum(if(state='approved', 1, 0))
写法一
select
concat(year(trans_date), '-', lpad(month(trans_date), 2, '0')) as `month`,
country,
count(id) as trans_count,
sum(if(state='approved', 1, 0)) as approved_count,
sum(amount) as trans_total_amount,
sum(if(state='approved', amount, 0)) as approved_total_amount
from Transactions
group by year(trans_date), month(trans_date) , country
执行用时分布601ms,击败57.76%使用 MySQL 的用户
写法二
select
date_format(trans_date, '%Y-%m') as `month`,
country,
count(id) as trans_count,
count(if(state='approved', 1, null)) as approved_count,
sum(amount) as trans_total_amount,
sum(if(state='approved', amount, 0)) as approved_total_amount
from Transactions
group by `month`, country
执行用时分布 852ms,击败28.66%使用 MySQL 的用户