0

我的表看起来与此类似:

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

我可以使用以下代码在一年内对 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 代码中。

抱歉对我的问题的解释不好,但我不知道如何更好地解释它。谢谢大家的回复。

4

1 回答 1

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;
于 2013-06-06T18:01:08.723 回答