Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何查询客户的借贷总余额?_Sql_Sql Server_Sum_Pivot_Aggregate Functions - Fatal编程技术网

Sql 如何查询客户的借贷总余额?

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

问题:我有一个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 -cost end) as balance
from mytable
group by customer

sum()
中的
case
表达式根据是贷记还是借记增加或减少成本。

FYI您希望显示您的尝试。