返回介绍

solution / 1100-1199 / 1193.Monthly Transactions I / README_EN

发布于 2024-06-17 01:03:22 字数 3054 浏览 0 评论 0 收藏 0

1193. Monthly Transactions I

中文文档

Description

Table: Transactions

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| id      | int   |
| country     | varchar |
| state     | enum  |
| amount    | int   |
| trans_date  | date  |
+---------------+---------+
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enum of type ["approved", "declined"].

 

Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
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 |
+------+---------+----------+--------+------------+
Output: 
+----------+---------+-------------+----------------+--------------------+-----------------------+
| month  | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
+----------+---------+-------------+----------------+--------------------+-----------------------+
| 2018-12  | US    | 2       | 1        | 3000         | 1000          |
| 2019-01  | US    | 1       | 1        | 2000         | 2000          |
| 2019-01  | DE    | 1       | 1        | 2000         | 2000          |
+----------+---------+-------------+----------------+--------------------+-----------------------+

Solutions

Solution 1: Grouping and Aggregation

We can first group by month and country, and then use the COUNT and SUM functions to respectively calculate the number of transactions, the number of approved transactions, the total amount, and the total amount of approved transactions for each group.

# Write your MySQL query statement below
SELECT
  DATE_FORMAT(trans_date, '%Y-%m') AS month,
  country,
  COUNT(1) AS trans_count,
  SUM(state = 'approved') AS approved_count,
  SUM(amount) AS trans_total_amount,
  SUM(IF(state = 'approved', amount, 0)) AS approved_total_amount
FROM Transactions
GROUP BY 1, 2;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文