Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I can't sum total amount of transactions in Money #221

Open
Teslima02 opened this issue May 15, 2024 · 1 comment
Open

I can't sum total amount of transactions in Money #221

Teslima02 opened this issue May 15, 2024 · 1 comment

Comments

@Teslima02
Copy link

What am trying to achieve

I want to be able to query total transaction with the sum function and money composite type

query =
  __MODULE__
  |> select([transaction], %{
    total_amount: type(sum(transaction.amount), transaction.amount),
  })

Repo.all(query)

The problem
I am using elixir money library and each time I ran the query I got the following error

** (Postgrex.Error) ERROR 42883 (undefined_function) function sum(money_with_currency) does not exist
     
         query: SELECT sum(t0."amount")::money_with_currency FROM "transactions" AS t0 WHERE (t0."business_id" = $1)
     
         hint: No function matches the given name and argument types. You might need to add explicit type casts.

I searched for the issue but solutions I found it not working for me, I checked similar issue on elixir forum.

https://elixirforum.com/t/ecto-how-to-sum-a-field-with-money-datatype/26736/4

Proposed solution but is not working

@Teslima02 Teslima02 changed the title I can't sum total amount of transaction in Money I can't sum total amount of transactions in Money May 16, 2024
@epd
Copy link

epd commented Jul 10, 2024

Just encountered this. You can use fragment/2 to get the sum:

total_amount: sum(fragment("(?).amount", field(transaction, :amount)))

This roughly translates to the following Postgres query:

select sum((transactions.amount).amount) from transactions;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants