我有下表:
listId | accountId | amount
1 1 20
1 1 20
2 2 30
2 2 30
我需要SUM(amount)
并按listId, accountId
分组才能得到结果:
listId | accountId | amount |
1 1 40
2 2 60
但这对我不起作用:SUM(amount) ... GROUP BY listId, accountId
我的完整查询是:
select `account_transactions`.*,
`enterprise_invoces`.*,
ABS(SUM(IF(AT_amount>0, AT_amount, 0))) AS debit,
ABS(SUM(IF(AT_amount<0, AT_amount, 0))) AS credit
from `account_transactions`
inner join `enterprise_invoces`
on `enterprise_invoces`.`AC_id` = `account_transactions`.`AT_code`
where `AT_createuser` = 15 and
date(`AT_transactiondatetime`) >= 2019-04-11 and
date(`AT_transactiondatetime`) <= 2019-07-29 and
`AC_code` >= 601 and
`AC_code` <= 761
group by `enterprise_invoces`.`AC_id`, `account_transactions.AT_transactionficheno`
order by `AT_transactiondatetime` desc
答案 0 :(得分:1)
您的选择查询不应包含其他列,并且应该仅包含group by中提到的列以及需要聚合的列。因此查询应如下所示。
选择
排序enterprise_invoces
。AC_id
,account_transactions.AT_transactionficheno
, ABS(SUM(IF(AT_amount> 0,AT_amount,0)))AS借方, ABS(SUM(IF(AT_amount <0,AT_amount,0)))AS信用 来自account_transactions
内部联接enterprise_invoces
在enterprise_invoces
上。AC_id
=account_transactions
。AT_code
其中AT_createuser
= 15且 date(AT_transactiondatetime
)> = 2019-04-11和 date(AT_transactiondatetime
)<= 2019-07-29和AC_code
> = 601并AC_code
<= 761 按enterprise_invoces
分组。AC_id
,account_transactions.AT_transactionficheno
按AT_transactiondatetime
desc