Make your choice

Transacciones Del Mes I

Escribe una consulta SQL para encontrar el número de transacciones y monto total, número de transacciones aprobadas y el monto total por cada mes y país. Regresa el resultado en cualquier orden.

#database#basic-aggregate

Tabla: Transactions

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

- `id` es la llave primaria para esta tabla.
- La tabla contiene impormación acerca de las transacciones entrantes.
- La columna `state` es un ENUM de tipo ['approved', 'declined'].

El formato del resultado se muestra en el siguiente ejemplo.

Ejemplo 1:

Entrada:
Tabla Transactions:
+------+---------+----------+--------+------------+
| 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 |
+------+---------+----------+--------+------------+

Salida:

+----------+---------+-------------+----------------+--------------------+-----------------------+
| 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                  |
+----------+---------+-------------+----------------+--------------------+-----------------------+

Solución:

SELECT
  DATE_FORMAT(trans_date, '%Y-%m') month,
  country,
  count(*) AS trans_count,
  sum(CASE
    WHEN state = 'approved' THEN 1
    ELSE 0 END) AS approved_count,
  sum(amount) AS trans_total_amount,
  sum(CASE
    WHEN state = 'approved' THEN amount
    ELSE 0 END) AS approved_total_amount
FROM transactions GROUP BY country, month;

slackmart blog © 2024