我在尝试计算列
时遇到了一些麻烦DF1
Date transaction_number tender_amt tender_type
2017-01-01 001 20 euros
2017-01-01 001 10 american
2017-01-01 002 20 american
2017-01-02 001 40 american
2017-01-01 003 40 euros
2017-01-01 004 50 american
如何创建一个根据交易编号和日期将tender_amt与euro / american分开的计算列?
DF-期望
Date transaction_number tender_amt tender_type exchange_rate(euro/american)
2017-01-01 001 20 euros 2
2017-01-01 001 10 american 2
2017-01-01 002 20 american (null)
2017-01-02 001 40 american (null)
2017-01-01 003 40 euros (null)
2017-01-01 004 50 american (null)
我的尝试
Select Date, transaction_number, tender_amt, tender_type,
exchange_rate = (Select O.tender_amt / B.tender_amt as exchange_rate
From df1 O
Inner Join df1 as B on B.Date = O.Date and B.transaction_number = O.transaction_number
where O.transaction_number = a.transaction_number
and O.Date = a.Date and O.tender_type = 'euro' and B.tender_type = 'american'
)
from df1 a
有没有更好的方法?
答案 0 :(得分:2)
让我假设SQL Server。您可以使用窗口函数:
select df1.*,
(max(case when tender_type = 'euros' then tender_amt end) over (partition by Date, transaction_number) /
max(case when tender_type = 'american' then tender_amt end) over (partition by Date, transaction_number)
) as exchange_rate
from df1;