My original question

When I execute the following query in SQLite, I get this error:

Query Error: misuse of aggregate: sum() Unable to execute statement

When I change the name of the "Loan" column to something like loan_amount the error goes away and my query works fine. Why is there a problem with "Loan"?

select
    t.*

    , coalesce(sum(ded0.after_tax_ded_amt), 0) as "Loan"

    , coalesce(sum(ded1.after_tax_ded_amt), 0) as ee_advance_amount

from totals t

  left join totals as ded0
    on t.ee_ssn = ded0.ee_ssn
    and t.deduction_code = "Loan"
    and ded0.deduction_code = "Loan"

  left join totals as ded1
    on t.ee_ssn = ded1.ee_ssn
    and t.deduction_code = "EE Advance"
    and ded1.deduction_code = "EE Advance"

group by t.ee_ssn;

Mid-post revelation

I'm pretty sure I figured out why I get the error, is it because I am comparing to "Loan" in the on-clause of my joins?

If so, how can I still use the word "Loan" for my column name in the output of my query?

1

There are 1 best solutions below

0
On BEST ANSWER

I'd guess that your real problem is quote misuse. Single quotes in SQL are for quoting string literals, double quotes are for quoting column and table names that need to be case sensitive or contain odd characters. SQLite is fairly forgiving of odd syntax so it is probably making a guess about what "Loan" means and guessing incorrectly. Try this:

select
    t.*
    , coalesce(sum(ded0.after_tax_ded_amt), 0) as "Loan"
    , coalesce(sum(ded1.after_tax_ded_amt), 0) as ee_advance_amount
from totals t
  left join totals as ded0
    on t.ee_ssn = ded0.ee_ssn
    and t.deduction_code = 'Loan'
    and ded0.deduction_code = 'Loan'
  left join totals as ded1
    on t.ee_ssn = ded1.ee_ssn
    and t.deduction_code = 'EE Advance'
    and ded1.deduction_code = 'EE Advance'
group by t.ee_ssn;