如何在不使用循环的情况下列出sql中的每个帐户信息和总和

时间:2014-10-07 01:16:44

标签: sql sql-server

大家好,我在回答这个问题时遇到了问题...

对于每个账户清单,事件数量,存款金额,提款金额以及存款和取款金额。我遇到了这背后的逻辑问题。 我一直在想,这需要一个循环,但我知道这不正确......有没有人知道如何解决这个问题?

Database/Table structure: 
Account (accountNo, ownerNo, balance)
Owner (ownerNo, firstName, lastName)
Event (id, accountNo, event, amount, eventDate)

我尝试过的代码:

SELECT COUNT(event) AS 'Account 1 number of events'
FROM Event
WHERE accountNo = 1

然后从那里继续列出帐户 - 但是对于可重用性而言,这对每个帐户都不起作用且效率不高。

1 个答案:

答案 0 :(得分:2)

试试这个:

select
  account.accountNo,
  count(1) as number_of_events,
  sum(case when event.amount > 0 then event.amount else 0 end) as deposits,
  sum(case when event.amount < 0 then event.amount else 0 end) as withdrawals,
  sum(event.amount) as sum_deposits_withdrawals
from
  account
inner join
  event on
  event.accountNo = account.accountNo
group by
  account.accountNo