【SQL】1193. 每月交易 I 【年月日(日期)拼接相关函数】

前述

知识点学习:

题目描述

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 的用户

相关推荐

  1. 【LeetCode】1193. 每月交易 I

    2024-03-17 07:32:01       56 阅读
  2. sql日期函数

    2024-03-17 07:32:01       35 阅读
  3. SQL日期函数

    2024-03-17 07:32:01       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-17 07:32:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-17 07:32:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-17 07:32:01       87 阅读
  4. Python语言-面向对象

    2024-03-17 07:32:01       96 阅读

热门阅读

  1. Android什么情况下会出现内存泄漏以及怎么解决?

    2024-03-17 07:32:01       47 阅读
  2. 远程调用初体验笔记

    2024-03-17 07:32:01       43 阅读
  3. [做题] 滑动窗口

    2024-03-17 07:32:01       47 阅读
  4. ArrayList 源码解析和设计思路

    2024-03-17 07:32:01       34 阅读