sql查询中的累积和

时间:2013-10-12 00:52:36

标签: sql sql-server sum

我有查询(下方),在“每月”列中显示数据。

Result

但我需要将此查询重写为累积总和,如图所示第三列。 我该怎么做? 谢谢你的回复。

我当前的查询:

select cast( ( Prodej.Ce_Jedn * Prodej.Mnoz ) / 1000 as numeric(15,2) ) as "Monthly" ,
       YEAR(  FAV.vatDate ) as "Rok" ,
       month( FAV.VatDate ) as "Měsíc" 
from Prodej
join FAKTVYDA FAV on FAV.Ci   = PRODEJ.C_Fak
                 and FAV.Rada = PRODEJ.R_Fak
where YEAR(FAV.VATDate) > year(getdate())-3
  and FAV.Rada in ('10','20','30','60') 
  and PRODEJ.C_Fak <> 0
  and '@{Stredisko.ParameterValue}' = case Prodej.Str 
                                        when ''  then FAV.Str
                                        when '-' then FAV.Str 
                                        else     Prodej.str
                                      end
order by month(FAV.VatDate)

2 个答案:

答案 0 :(得分:0)

使用SUM语句时,查询还需要GROUP BY语句。 这不包含在上面的查询中,所以它不起作用。

答案 1 :(得分:-1)

您可以通过在要汇总的字段前面使用SUM语句来实现此目的。请参阅this帖子,其中提供了适合您问题的解决方案。

select cast( ( Prodej.Ce_Jedn * Prodej.Mnoz ) / 1000 as numeric(15,2) ) as "Monthly" ,
YEAR(  FAV.vatDate ) as "Rok" ,
month( FAV.VatDate ) as "Měsíc" 
SUM(( Prodej.Ce_Jedn * Prodej.Mnoz ) / 1000 as numeric(15,2) ) as "Cumulative"
from Prodej
join FAKTVYDA FAV on FAV.Ci   = PRODEJ.C_Fak
and FAV.Rada = PRODEJ.R_Fak
where YEAR(FAV.VATDate) > year(getdate())-3
and FAV.Rada in ('10','20','30','60') 
and PRODEJ.C_Fak <> 0
and '@{Stredisko.ParameterValue}' = case Prodej.Str 
when ''  then FAV.Str
when '-' then FAV.Str 
else     Prodej.str
end
order by month(FAV.VatDate)

希望有所帮助,

克里斯