我的表格看起来与此类似:
LocalAmount Firm_id Date StoreCard_Id
1000 5532 46,545 14124
2000 5325 46,545 13124
30000 25235 46,545 14141
1500 2525 46,545 14214
2134 25235 46,545 14241
144150 2525 46,545 41441
我可以使用以下代码在一年内使用SUM localAmount:
select sum(II2.LocalTAmountWithoutVAT) as "Celkem"
from IssuedInvoices2 II2
join IssuedInvoices II on II.id = II2.parent_id
join firms F on F.id = II.firm_id
left join StoreCards SC on II2.StoreCard_ID = SC.ID
left join ABI_StoreCardsWithMenu(sc.ID) SCWM on SCWM.OUT_StoreCard_ID = SC.id
where
ib_decodedate_year(II.docdate$date) = EXTRACT(YEAR FROM CURRENT_DATE)
and F.id = '@{_firmID}'
group by
out_menu1Text
order by
out_menu1Text
但我需要做两年相同的事情并减少这两个SUMS。它必须在一个SQL代码中。
很抱歉我的问题解释不好,但我不知道如何更好地解释它。 感谢所有回复。
答案 0 :(得分:3)
您可以使用条件聚合执行此操作:
select sum(case when ib_decodedate_year(II.docdate$date) = EXTRACT(YEAR FROM CURRENT_DATE)
then II2.LocalTAmountWithoutVAT
else 0
end) as ThisYear,
sum(case when ib_decodedate_year(II.docdate$date) = EXTRACT(YEAR FROM CURRENT_DATE) - 1
then II2.LocalTAmountWithoutVAT
else 0
end) as LastYear,
(sum(case when ib_decodedate_year(II.docdate$date) = EXTRACT(YEAR FROM CURRENT_DATE)
then II2.LocalTAmountWithoutVAT
else 0
end) -
sum(case when ib_decodedate_year(II.docdate$date) = EXTRACT(YEAR FROM CURRENT_DATE) - 1
then II2.LocalTAmountWithoutVAT
else 0
end)
) as Diff
from IssuedInvoices2 II2 join
IssuedInvoices II
on II.id = II2.parent_id join
firms F
on F.id = II.firm_id left join
StoreCards SC on II2.StoreCard_ID = SC.ID left join
ABI_StoreCardsWithMenu(sc.ID) SCWM
on SCWM.OUT_StoreCard_ID = SC.id
where F.id = '@{_firmID}'
group by out_menu1Text
order by out_menu1Text;