我目前正在尝试编写一个select语句,用于计算单个列中的年度总和。
我面临的问题是有几种不同的付款频率,例如我必须将每月的数量乘以12以获得年度,每季度增加4,半年增加2等。
我在下面写了一个声明,但是它要求我按频率和数量字段进行分组,这会产生不希望的结果。
select (case when Frequency='month' then SUM(cast(Amount as decimal(10,2))*12)
else (case when Frequency='quarter' then SUM(cast(Amount as decimal(10,2))*4)
else (case when Frequency='year' then SUM(cast(Amount as decimal(10,2))*1)
else (case when Frequency='six months' then SUM(cast(Amount as decimal(10,2))*2) end)
end)
end) end) as 'Total Annual Amount'
from Table group by Frequency
我知道我可能会在解决这个问题时咆哮错误的树,但上面是我最接近的。
希望我有足够的描述性,如果你需要我进一步详细说明,请告诉我
答案 0 :(得分:1)
尝试将您的金额移到案例之外:
select
sum (case when Frequency='Month' then (cast(amount as decimal(10,2))*12
when Frequency='quarter' then...
end) as [Total Annual Amount]
答案 1 :(得分:0)
您也可以使用WITH AS(假设是ORACLE)......
WITH dmap AS
( select 'Month' as duration, 12 as mult from dual
UNION
select 'Year' as duration, 1 as mult from dual
UNION
select 'Quater' as duration, 4 as mult from dual
UNION
select 'six months' as duration, 2 as mult from dual
)
select sum(cast(Amount as decimal(10,2)) * mult)
from tab, dmap
where duration = frequency;