essay

hot50-每月交易I

#mysql

hot50——每月交易I

表:Transactions

Column Name Type
id int
country varchar
state enum
amount int
trans_date date

id 是这个表的主键。
该表包含有关传入事务的信息。
state 列类型为 ["approved", "declined"] 之一。

编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

以 任意顺序 返回结果表。

查询结果格式如下所示。

示例 1:

输入:
Transactions table:

id country state amount trans_date
121 US approved 1000 2018-12-18
122 US declined 2000 2018-12-19
123 US approved 2000 2019-01-01
124 DE approved 2000 2019-01-07

输出:

month country count acount tamount atamount
2018-12 US 2 1 3000 1000
2019-01 US 1 1 2000 2000
2019-01 DE 1 1 2000 2000

答:

使用case更常用:

select 
    date_format(trans_date, '%Y-%m') as month,
    country,
    count(*) as count,
    sum(case when state = 'approved' then 1 else 0 end) as acount,
    sum(amount) as tamount,
    sum(case when state = 'approved' then amount else 0 end) as atamount
from 
    transactions
group by 
    month, country;
select 
    date_format(trans_date, '%Y-%m') as month,
    country,
    count(*) as count,
    sum(if(state = 'approved', 1, 0)) as acount,
    sum(amount) as tamount,
    sum(if(state = 'approved', amount, 0)) as atamount
from 
    transactions
group by 
    month, country

使用if的话就不需要then,else,end。
解析:

  1. DATE_FORMAT(trans_date, '%Y-%m') AS month
    作用:将日期字段 trans_date 格式化为 YYYY-MM 格式(例如 2018-12),并命名为 month。
    目的:实现按“月”进行分组统计。
  2. COUNT(*) AS count
    作用:统计当前分组(某月某国)内的总行数。
    对应:对应你要求的 count 列(事务总数)。
  3. SUM(IF(state = 'approved', 1, 0)) AS acount
    作用:条件求和。如果状态是 approved 则计为 1,否则为 0。
    对应:对应你要求的 acount 列(已批准的事务数)。
  4. SUM(amount) AS tamount
    作用:直接对 amount 列求和。
    对应:对应你要求的 tamount 列(事务总金额)。
  5. SUM(IF(state = 'approved', amount, 0)) AS atamount
    作用:条件求和。只有当状态是 approved 时,才将 amount 计入总和。
    对应:对应你要求的 atamount 列(已批准的总金额)。
  6. GROUP BY month, country
    作用:按照“月份”和“国家”进行分组,确保统计数据是针对每一个“月-国”组合单独计算的。
comments如果有不同意见或者补充,直接留在这里。
contact

在别处继续找到我

如果你想聊技术、设计,或者只是打个招呼。

暂未配置外部链接