0

我原来的问题

当我在 SQLite 中执行以下查询时,我收到此错误:

查询错误:误用聚合:sum() 无法执行语句

当我将"Loan"列的名称更改为loan_amount错误消失并且我的查询工作正常时。为什么有问题"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;

中后期启示

我很确定我知道为什么会出现错误,是因为我"Loan"在与我的联接的 on-clause 进行比较吗?

如果是这样,我如何在查询输出中仍然使用“贷款”一词作为我的列名?

4

1 回答 1

0

我猜你真正的问题是引用滥用。SQL 中的单引号用于引用字符串文字,双引号用于引用需要区分大小写或包含奇数字符的列名和表名。SQLite 对奇怪的语法相当宽容,因此它可能会猜测是什么"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;
于 2011-07-31T20:57:11.083 回答