简体   繁体   English

带修饰符的SQL平均值

[英]SQL average value with modifiers

I have a following data in my Oracle SQL database: 我的Oracle SQL数据库中有以下数据:

VALUE   CURRENCY
143.88  PLN
440     PLN
21      USD
210.46  PLN
104.17  CHF
324.5   USD
198.84  PLN

What I want to do is to calculate an average value taking into account there are different currencies. 我要做的是考虑到不同的货币来计算平均值。 What is the easiest method to do this? 最简单的方法是什么?

Right now I'm creating multiple columns with all desired values, but I have a problem with choosing right value according to currency in particular row. 现在,我正在创建具有所有期望值的多列,但是在根据特定行中的货币选择正确的值时遇到了问题。

SELECT VALUE,VALUE*3.08,VALUE*3.37,CURRENCY
  FROM DATA_SAMPLE
    WHERE VALUE IS NOT NULL

Lets keep it normalised, for easy querying. 让它保持标准化,以便于查询。 Have 2 tables Say, 有2张桌子说,

Price (CurrencyCode,Value)

And

Currency_Conversion(CurrencyCode, CurrencyName,conversion_factor)

Price: 价钱:

VALUE   CURRENCYCODE
143.88  PLN
440     PLN
21      USD
210.46  PLN
104.17  CHF
324.5   USD
198.84  PLN

Currency_Conversion: 货币转换:

CURRENCYCODE CONVFACTOR
PLN          3.08
USD          1
CHF          3.37

Query: 查询:

SELECT CONV.CURRENCYCODE , AVG(PRICE.VALUE * CONV. CONVFACTOR) as VALUE
FROM PRICE, CURRENCY_CONVERSION CONV
WHERE
     PRICE. CURRENCYCODE = CONV. CURRENCYCODE
GROUP BY
     CONV. CURRENCYCODE

I would go with the lookup table solution, but if you can't do that, here is a query that may help you. 我会使用查找表解决方案,但是如果您不能这样做,那么以下查询可能会为您提供帮助。

SELECT
  case
    when currency = 'USD' then value*2.1
    when currency = 'PLN' then value*[INSERT PLN CURRENCY HERE]
  end
FROM DATA_SAMPLE
WHERE VALUE IS NOT NULL

I would write function which takes currency code and returns current conversion rate. 我会写一个函数,该函数需要货币代码并返回当前的转换率。 Then I would use this function to normalize values - convert them into one currency. 然后,我将使用此函数对值进行规范化-将它们转换为一种货币。 Then I would calculate average. 然后,我将计算平均值。

Kind of pseudo sql (I'm not Oracle expert :)) 一种伪SQL(我不是Oracle专家:))

CREATE FUNCTION FunctionConvertCurrency
...

SELECT AVG(VALUE*FunctionConvertCurrency(CURRENCY))
FROM DATA_SAMPLE

Create a table with currency prices. 创建一个包含货币价格的表。 Let's say PRICES with columns CURRENCY and PRICE . 假设PRICESCURRENCYPRICE列。 Then select the average value: 然后选择平均值:

SELECT avg(ds.value*p.price) FROM data_sample ds JOIN prices p ON ds.currency = p.currency WHERE ds.value is not null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM