[英]How to create view to calculate currencies?
我有以下表格:
Products
product, idcurrency, value
Prod1 1 5000
Prod2 2 3000
Prod3 3 2000
Currrency
idcurrency, currencyID
1 EUR
2 USD
3 DKK
ForexExchange
idforexExchange providername, idbaseCurrency, isActive
1 XE Eur 1
2 provider2 DKK 1
ForexRates
idForexRates idforexExchange, toCurrency, exchangeRate
1 1 AED 2.3
2 1 EGY 1.3
3 1 GBP 2.4
4 2 AED 7.3
5 3 EGY 6.4
6 4 GBP 3.4
我想獲取所有產品的有效貨幣為美元。
-所有與查詢表“貨幣”相關的幣種-我們有forexxchange表,因此,如果我們有多個匯率提供者,我們將根據基礎貨幣獲得每個交易所的幣種匯率
-匯率表保存每次兌換的匯率
-我們可以從isActive設置活躍匯率,因此該匯率表將在系統中使用
Expected Results
product Value ValueUSD
prod1 5000 25000
...............
開始了:
-- sample data, for somebody else start
CREATE TABLE #Product
( Name varchar(50), IdCurrency int, Value decimal(15,2) )
CREATE TABLE #Currency
( IdCurrency int, CurrencyID char(3) )
CREATE TABLE #ForexExchange
( IdForexExchange int, IdBaseCurrency char(3), IsActive bit)
CREATE TABLE #ForexRates
( IdForexRates int, IdForexExchange int,
ToCurrency char(3), ExchangeRate decimal(15,2) )
GO
INSERT INTO #Product VALUES ('Prod1', 1, 5000)
INSERT INTO #Product VALUES ('Prod2', 2, 3000)
INSERT INTO #Product VALUES ('Prod3', 3, 2000)
INSERT INTO #Currency VALUES (1, 'EUR')
INSERT INTO #Currency VALUES (2, 'USD')
INSERT INTO #Currency VALUES (3, 'DKK')
INSERT INTO #ForexExchange VALUES (1, 'EUR', 1)
INSERT INTO #ForexExchange VALUES (2, 'DKK', 1)
INSERT INTO #ForexRates VALUES (1, 1, 'AED', 2.3)
INSERT INTO #ForexRates VALUES (2, 1, 'EGY', 1.3)
INSERT INTO #ForexRates VALUES (3, 1, 'GBP', 2.4)
INSERT INTO #ForexRates VALUES (4, 2, 'AED', 7.3)
INSERT INTO #ForexRates VALUES (5, 3, 'EGY', 6.4)
INSERT INTO #ForexRates VALUES (6, 4, 'GBP', 3.4)
GO
和您的視圖聲明:
SELECT
#Product.Name,
#Currency.CurrencyID as FromCurrency,
#ForexRates.ToCurrency,
#ForexRates.ExchangeRate,
#Product.Value as OriginalValue,
#Product.Value * #ForexRates.ExchangeRate as CalculatedValue
FROM
#Product LEFT JOIN
#Currency ON #Product.IdCurrency = #Currency.IdCurrency LEFT JOIN
#ForexExchange ON
IsActive = 1 AND
#Currency.CurrencyID = #ForexExchange.IdBaseCurrency LEFT JOIN
#ForexRates ON #ForexExchange.IdForexExchange = #ForexRates.IdForexExchange
--WHERE
-- #ForexRates.ToCurrency = 'USD'
我沒有評論WHERE
子句,因為您沒有任何美元貨幣可以顯示。 您不應該在查詢中包含該過濾器,因為它可以重復使用以任何貨幣顯示該產品值:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.