我有一个数据集,我想按类别(项目)对值进行求和,但是在将它们求和之前,我需要转换依赖于另一列中货币的某些值的货币。
样本数据集:
Item Currency Value
1 USD 10
1 PHP 100
2 USD 50
2 PHP 1000
3 PHP 500
select ITEM,
(case when CURRENCY='usd' then sum(VALUE*2) else sum(VALUE) end ) VALUE
from TABLE1
inner join TABLE2 on TABLE1.ID=TABLE2.ID
inner join TABLE3 on TABLE3.X=TABLE1.X
inner join TABLE4 on TABLE1.Y=TABLE4.Y
where A=1 and B=2 and C=5
group by ITEM, CURRENCY
ORDER BY ITEM asc
所需的结果(将x2作为从USD转换为PHP的因数):
Item Value
1 120
2 1100
3 500
但是,我得到以下信息,它已正确转换了货币,但未按项目分组(即,我正在获取项目的重复行,而不是具有累加值的1行):
Item Value
1 20
1 100
2 100
2 1000
3 500
答案 0 :(得分:1)
case
应该是SUM()
的参数:
select ITEM,
sum(case when CURRENCY='usd' then VALUE*2 else VALUE
end ) as VALUE
from TABLE1 join
TABLE2
on TABLE1.ID = TABLE2.ID join
TABLE3
on TABLE3.X = TABLE1.X join
TABLE4
on TABLE1.Y = TABLE4.Y
where A = 1 and B = 2 and C = 5
group by ITEM
ORDER BY ITEM asc;
注意:GROUP BY
仅靠ITEM
,因为它定义了结果集中所需的行。