2010-02-19 14 views
4

J'ai la requête SQL suivante:Puis-je combiner un PIVOT avec une jointure interne dans Microsoft SQL Server?

SELECT CountryID, [10201] AS CountryGDPPerCapita, [10677] AS LifeExpTotal 
FROM 
(
    SELECT CountryID,FieldID,numeric 
    FROM globaledge.dbo.DIBS_Data 
    WHERE CountryID IN (3,5) 
    AND FieldID IN (10201,10677) 
    AND year = 2002 
) SourceTable 
PIVOT 
(
    MAX(numeric) 
    FOR FieldID IN ([10201],[10677]) 
) AS PivotTable 
ORDER BY PivotTable.CountryID 

Cela renvoie quelque chose qui ressemble à ceci:

CountryID CountryGDPPerCapita LifeExpTotal

3 35985,78 77,24

5 9147,7 74,54

Ensuite, J'ai une autre question comme suit:

SELECT CountryName, CountryGDP, CountryGDPGrowth 
FROM globaledge.dbo.Country_Statistics 
WHERE CountryID IN (3,5) 
AND year=2002 
Order By CountryName 

qui produit les éléments suivants:

CountryName CountryGDP CountryGDPGrowth

Mexique 1567000000000000 1.3

États-Unis 14440000000000000 0,4

Notez également, j'ai CountryID dans les deux tableaux, qui se réfèrent dans le même pays. Ce que je veux est de créer une requête SQL, peut-être avec un INNER JOIN, qui renverrait les éléments suivants:

CountryName CountryGDP CountryGDPGrowth CountryGDPPerCapita LifeExpTotal

Mexique 156700000000000000 1.3 35985,78 77,24

États-Unis 144400000000000000 0,4 9147,7 74,54

Quelqu'un peut-il m'aider à faire cette demande? ou dites-moi si c'est possible?

Répondre

11

Quelque chose comme ça fonctionnerait:

SELECT 
    a.CountryID, a.CountryName, a.CountryGDP, a.CountryGDPGrowth 
, b.CountryGDPPerCapita, b.LifeExpTotal 
FROM 
(
    SELECT CountryID, CountryName, CountryGDP, CountryGDPGrowth 
    FROM globaledge.dbo.Country_Statistics 
    WHERE CountryID IN (3,5) 
    AND year=2002 
) AS a 
JOIN 
(
    SELECT CountryID, [10201] AS CountryGDPPerCapita, [10677] AS LifeExpTotal 
    FROM 
    (
     SELECT CountryID,FieldID,numeric 
     FROM globaledge.dbo.DIBS_Data 
     WHERE CountryID IN (3,5) 
     AND FieldID IN (10201,10677) 
     AND year = 2002 
    ) SourceTable 
    PIVOT 
    (
     MAX(numeric) 
     FOR FieldID IN ([10201],[10677]) 
    ) AS PivotTable 
) AS b ON a.CountryID = b.CountryID 
Order By a.CountryName