Creating a view in SQL Server

Question

I have 2 tables:

  • Contracts (ContactID, ContractNo, estimatedCost, CurrencyEstimatedCostID, ContractCost, CurrencyContractCostID)

  • CurrencyTypes (CurrencyID, CurrencyTypeName).

I want to view the contract table with CurrencyTypeName in place of the Foreign Keys CurrencyEstimatedCostID and CurrencyContractCostID in the view (in the SQL Server view).

I use this query but it return just one column for CurrencyTypeName (I want one column for each of CurrencyEstimatedCostID and CurrencyContractCostID).

SELECT 
    Contracts.contractID, Contracts.ContractNo, CurrencyTypes.CurrencyType
FROM 
    Contracts 
INNER JOIN 
    CurrencyTypes ON Contracts.CurrencyEstimatedCostID = CurrencyTypes.CurrencyType 
                     AND Contracts.CurrencyContractCostID = CurrencyTypes.CurrencyType

How do I change the query?

marc_s

Not 100% sure if I understand what you're trying to do - but if you have two columns that both act as foreign key into the CurrencyTypes table, you need to join twice:

SELECT 
    c.contractID, c.ContractNo, 
    EstimatedCostCurrency = ct1.CurrencyType, 
    ContractCostCurrency = ct2.CurrencyType
FROM 
    Contracts  c
INNER JOIN 
    CurrencyTypes ct1 ON c.CurrencyEstimatedCostID = ct1.CurrencyID
INNER JOIN 
    CurrencyTypes ct2 ON c.CurrencyContractCostID = ct2.CurrencyID

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related