Sql 如何查询客户的借贷总余额?
问题:我有一个SQL Server表,如下所示: 事务id 时间戳 顾客 成本 活动 123 10-12-2020 1. 60 信用 456 11-12-2020 2. 50 信用 789 11-12-2020 1. 20 借记 000 12-12-2020 3. 100 信用 999 15-12-2020 2. 50 借记Sql 如何查询客户的借贷总余额?,sql,sql-server,sum,pivot,aggregate-functions,Sql,Sql Server,Sum,Pivot,Aggregate Functions,问题:我有一个SQL Server表,如下所示: 事务id 时间戳 顾客 成本 活动 123 10-12-2020 1. 60 信用 456 11-12-2020 2. 50 信用 789 11-12-2020 1. 20 借记 000 12-12-2020 3. 100 信用 999 15-12-2020 2. 50 借记 您可以只使用条件聚合: select customer, sum(case when operation = 'credit' then cost else -co
您可以只使用条件聚合:
select customer,
sum(case when operation = 'credit' then cost else -cost end) as balance
from mytable
group by customer
sum()
中的case
表达式根据是贷记还是借记增加或减少成本。FYI您希望显示您的尝试。