我有一张桌子
Date, employee transaction amount 02-03-2015 e1 credit 400 02-03-2015 e1 debit 25 02-04-2015 e2 credit 600 02-04-2015 e2 debit 35 02-03-2015 e1 credit 400 02-03-2015 e1 debit 250
我想创建一个临时表,如下所示:
Date, employee transaction amount 02-03-2015 e1 credit 400 02-03-2015 e1 debit 25 02-03-2015 e1 NET_BAL 375 02-04-2015 e2 credit 600 02-04-2015 e2 debit 35 02-04-2015 e2 NET_BAL 565 02-04-2015 e1 credit 400 02-04-2015 e1 debit 250 02-04-2015 e1 NET_BAL 150
有人可以帮忙吗?我是SQL新手
答案 0 :(得分:0)
这是你 CAN 这样做的方式,而不是你 应该如何做到这一点。甚至PostgreSQL(或其他几个RDBMS系统)也可以操作数据来呈现非规范化和异构结果,表示层应该负责从服务器获取数据并将其分解并格式化,而不是数据库服务器。
with
data (date, employee, transaction, amount) as (values
('02-03-2015', 'e1', 'credit', 400),
('02-03-2015', 'e1', 'debit', 25),
('02-04-2015', 'e2', 'credit', 600),
('02-04-2015', 'e2', 'debit', 35),
('02-04-2015', 'e1', 'credit', 400),
('02-04-2015', 'e1', 'debit', 250)),
net as (
select date, employee, 'NET_BAL'::text as transaction, sum(case when transaction = 'debit' then -1 else 1 end * amount) as amount
from data
group by date, employee)
select * from data
union
select * from net
order by date, employee, transaction