Skip to content

Commit db6885d

Browse files
committed
feat: added the default grouping by month in sum_by_category
1 parent 68fd069 commit db6885d

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

src/main/resources/migrations/function_expense

Whitespace-only changes.
Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
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) 
33
AS $$
44
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;
1222
END;
1323
$$
14-
LANGUAGE plpgsql;
24+
LANGUAGE plpgsql;

0 commit comments

Comments
 (0)