我在我的数据库中有这个表,我试图得到2组值并将它们放在一个联合中。
这是表格。
我的工会基本上有两个条款,其中interest_payment> 0和interest_paid> 0,如果interest_payment大于零,它将占用该行并将其与下一行相加,如果下一行具有interest_payment> 0它将该行添加到该行,但是如果interest_payment< 0,它应该在同一行中添加interest_paid。但是现在当我运行查询时,我明白了。
基本上netInterest不应该显示Null,因为我使用的是sum,所以它应该只返回一行。
这是所有这些的sql。
Select sum(investedMoney) as investMoney , sum(estimatedEarning) as estimatedEarning , sum(NetInterest) as NetInterest, Eurosymbol
from
(
select sum(round(a.Amount * e.average_rate / f.average_rate, 2)) as investedMoney ,
sum(round((d.interest_payment + d.overdue_payment) * e.average_rate / f.average_rate, 2)) as estimatedEarning,
0 as NetInterest,
c.symbol as Eurosymbol
from investment a
inner join money_offer b
on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
inner join payment_plan d
on d.offer_orig_id = b.ORIG_ID and d.interest_payment > 0 and d.UPDATE_DT is null
inner join currency c
on d.currency = c.ID
inner join exchange_rates e
on e.currency_id = a.Currency
inner join exchange_rates f
on f.currency_id = a.Currency
where a.Owner = 533 and
a.UPDATE_DT is null
union
select 0 as investedMoney ,
0 as estimatedEarning,
sum(round((d.interest_paid+ d.overdue_paid) * e.average_rate / f.average_rate, 2)) as NetInterest,
c.symbol as Eurosymbol
from investment a
inner join money_offer b
on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
inner join payment_plan d
on d.offer_orig_id = b.ORIG_ID and d.interest_paid > 0 and d.UPDATE_DT is null
inner join currency c
on d.currency = c.ID
inner join exchange_rates e
on e.currency_id = a.Currency
inner join exchange_rates f
on f.currency_id = a.Currency
where a.Owner = 533 and
a.UPDATE_DT is null
)tmptbl
group by Eurosymbol;
答案 0 :(得分:1)
在d.interest_payment > 0
或d.interest_paid > 0
的情况下,您在payment_plan
表中存储不同的货币。我的猜测是你有虚拟ID来表示"没有货币"。假设您在currency.symbol
中为该特定虚拟货币存储了NULL值,您可以在整个查询中使用max
。
另外,我认为出于您的目的,您应该将union
个查询合并为一个。这样,您可以处理同一记录中两个条件都为真的情况:它们将不会被复制。两种类型的数字之间的区别可以使用case when
构造,如下所示:
select sum(case when d.interest_payment > 0
then round(a.Amount * e.average_rate / f.average_rate, 2)
else 0
end) as investedMoney,
sum(case when d.interest_payment > 0
then round((d.interest_payment + d.overdue_payment)
* e.average_rate / f.average_rate, 2)
else 0
end) as estimatedEarning,
sum(case when d.interest_paid > 0
then round((d.interest_paid + d.overdue_paid)
* e.average_rate / f.average_rate, 2)
else 0
end) as NetInterest,
max(c.symbol) as Eurosymbol
from investment a
inner join money_offer b
on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
inner join payment_plan d
on d.offer_orig_id = b.ORIG_ID and d.UPDATE_DT is null
and (d.interest_payment > 0 or d.interest_paid > 0)
inner join currency c
on d.currency = c.ID
inner join exchange_rates e
on e.currency_id = a.Currency
inner join exchange_rates f
on f.currency_id = a.Currency
where a.Owner = 533
and a.UPDATE_DT is null
您还应该检查为什么从exchange_rates
(e
和f
)两次加入完全相同的记录,这使得表达式e.average_rate / f.average_rate
始终评估为1(假设费率永远不会为零。)