累计和条件

时间:2014-10-31 12:20:58

标签: tsql sql-server-2012

我试图在我的查询中通过列week(如果可能,然后按列Datum$ADTE排序获得结果)获得累积总和:

select
      A.Castka "Amount",
      'Cashflow' as N,
      A.Datum$DATE "Datum",
      cast(A.Rok as varchar(4)) + '-' + cast(A.Tyden as varchar(4)) "Week"
  from iGateCashflow A
  where
     1 = 1
      and A.BusTransaction_ID = '1D00000101'
      and A.Vyjasneno = 'A'
      and cast(datepart(week ,convert(date, dbo.ib_DateToString(Napocteno$DATE, 'dd.mm.yyyy'), 104)) as varchar(4))
              =     44

where子句中是条件,这些条件将通过外部形式进行编辑。

我希望得到这样的结果(没有Amount列的情况下更好)

week      N     Amount      Result
44    Cashflow    150          150
45    Cashflow    200          350
46    Cashflow    300          650
47    Cashflow    350          1000

我尝试过这样的事情,但我无法实现预期的结果:

select
    sum(y.Amount),
    Y.N,
    Y.Week
from (
    select
        A.Castka "Amount",
        'Cashflow' as N,
        A.Datum$DATE "Datum",
        cast(A.Rok as varchar(4)) + '-' + cast(A.Tyden as varchar(4)) "Week"
    from iGateCashflow A
    where
        1 = 1
        and A.BusTransaction_ID = '1D00000101'
        and A.Vyjasneno = 'A'
        and cast(datepart(week ,convert(date, dbo.ib_DateToString(Napocteno$DATE, 'dd.mm.yyyy'), 104)) as varchar(4))
                =   44
) X
join (
    select
        A.Castka "Amount",
        'Cashflow' as N,
        cast(A.Rok as varchar(4)) + '-' + cast(A.Tyden as varchar(4)) "Week"
    from iGateCashflow A
    where
        1 = 1
        and A.BusTransaction_ID = '1D00000101'
        and A.Vyjasneno = 'A'
        and cast(datepart(week ,convert(date, dbo.ib_DateToString(Napocteno$DATE, 'dd.mm.yyyy'), 104)) as varchar(4))
                =   44
    )   Y on Y.Week <= X.Week
group by
    Y.N,
    Y.Week
order by
    Y.Week

3 个答案:

答案 0 :(得分:1)

最好使用OVER子句按周和按日期顺序获取Sum分区,请参阅 Over Clause

答案 1 :(得分:1)

我认为你的问题比你所展示的更多。但请将此作为一个想法(您需要添加WHERE条件等)

SELECT *,
       SUM(Amount) OVER (ORDER BY [week])
FROM   iGateCashflow

答案 2 :(得分:0)

也许尝试这样的事情

select
    cast(A.Rok as varchar(4)) + '-' + cast(A.Tyden as varchar(4)) "Week",
    sum(B.Castka) "Total amount"
from iGateCashflow A
inner join iGateCashflow B
    on A.BusTransaction_ID = B.BusTransaction_ID
    and A.Vyjasneno = B.Vyjasneno
    and B.week <= A.week --> if week is a calculated field, include the calculation here for both 'week's
where
    1 = 1
    and A.BusTransaction_ID = '1D00000101'
    and A.Vyjasneno = 'A'
    and cast(datepart(week ,convert(date, dbo.ib_DateToString(Napocteno$DATE, 'dd.mm.yyyy'), 104)) as varchar(4))
            =   44
group by cast(A.Rok as varchar(4)) + '-' + cast(A.Tyden as varchar(4)) "Week"