Ecto.Query.API.type/2 doesn't cast type for subquery value

I have the the query below which uses a subquery to sum amounts for all Transactions in an Account. The amount column is a Money.Ecto.Composite.Type. I’m calling Ecto.Query.API.type/2 in the subquery select.

However, the total_value that is returned in the struct is the raw tuple {"USD", Decimal.new("1000.0")} rather than a Money struct Money.new("1000.0").

If I do something similar in a regular query, the Money struct is returned as expected.

Any ideas why the value doesn’t get cast to a Money struct?

def get_accounts_by_business(business_id) do
    total_value_query =
      from t in Transaction,
        where: t.account_id == parent_as(:account).id,
        select:
          t.amount
          |> sum()
          |> type(t.amount)

    query =
      from a in Account,
        as: :account,
        where: a.business_id == ^business_id,
        select: %{
          a
          | total_value: subquery(total_value_query)
        }

    Repo.all(query)
end

amount is a field on the Transaction schema

    field :amount, Money.Ecto.Composite.Type, default_currency: :USD

total_value is a virtual field in the Account schema:

    field :total_value, Money.Ecto.Composite.Type, default_currency: :USD, virtual: true