|
1 | | -CREATE OR REPLACE FUNCTION sum_by_category(start_date DATE, end_date DATE) |
2 | | -RETURNS TABLE(account_id bigint, category_id bigint, total_amount DOUBLE PRECISION) |
| 1 | +CREATE OR REPLACE FUNCTION sum_by_category(start_date DATE, end_date DATE, interval TEXT = 'month') |
| 2 | +RETURNS TABLE(account_id bigint, category_id bigint, total_amount DOUBLE PRECISION) |
3 | 3 | AS $$ |
4 | 4 | BEGIN |
5 | | - RETURN QUERY |
6 | | - SELECT t.id_account, c.id AS category_id, SUM(t.amount) AS total_amount |
7 | | - FROM transaction t |
8 | | - JOIN category c ON t.category = c.id |
9 | | - WHERE t.created_at BETWEEN start_date AND end_date |
10 | | - GROUP BY t.id_account, c.id |
11 | | - ORDER BY t.id_account, total_amount DESC; |
| 5 | + IF interval = 'day' THEN |
| 6 | + RETURN QUERY |
| 7 | + SELECT t.id_account, c.id AS category_id, SUM(t.amount) AS total_amount |
| 8 | + FROM transaction t |
| 9 | + JOIN category c ON t.category = c.id |
| 10 | + WHERE t.created_at BETWEEN start_date AND end_date |
| 11 | + GROUP BY t.id_account, DATE(t.created_at) |
| 12 | + ORDER BY t.id_account, total_amount DESC; |
| 13 | + ELSE |
| 14 | + RETURN QUERY |
| 15 | + SELECT t.id_account, c.id AS category_id, SUM(t.amount) AS total_amount |
| 16 | + FROM transaction t |
| 17 | + JOIN category c ON t.category = c.id |
| 18 | + WHERE t.created_at BETWEEN start_date AND end_date |
| 19 | + GROUP BY t.id_account, MONTH(t.created_at) |
| 20 | + ORDER BY t.id_account, total_amount DESC; |
| 21 | + END IF; |
12 | 22 | END; |
13 | 23 | $$ |
14 | | -LANGUAGE plpgsql; |
| 24 | +LANGUAGE plpgsql; |
0 commit comments