我可以将 PIVOT 与 Microsoft SQL Server 中的内部联接结合起来吗?

Posted

技术标签:

【中文标题】我可以将 PIVOT 与 Microsoft SQL Server 中的内部联接结合起来吗?【英文标题】:Can I combine a PIVOT with an Inner join in microsoft SQL server? 【发布时间】:2011-01-18 21:37:41 【问题描述】:

我有以下 SQL 查询:

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

这会返回如下所示的内容:

CountryID CountryGDPPerCapita LifeExpTot​​al

3 35985.78 77.24

5 9147.7 74.54

那我还有一个查询如下:

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

这会产生以下内容:

CountryName CountryGDP CountryGDPGrowth

墨西哥 1567000000000000 1.3

美国 14440000000000000 0.4

另外请注意,我在两个表中都有 CountryID,它们指的是同一个国家。我想要的是创建一个 SQL 查询,可能带有一个 INNER JOIN,它将返回以下内容:

CountryName CountryGDP CountryGDPGrowth CountryGDPPerCapita LifeExpTot​​al

墨西哥 156700000000000000 1.3 35985.78 77.24

美国 144400000000000000 0.4 9147.7 74.54

谁能帮我做这个查询?或者告诉我这是否可能?

【问题讨论】:

【参考方案1】:

这样的事情会起作用:

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

【讨论】:

以上是关于我可以将 PIVOT 与 Microsoft SQL Server 中的内部联接结合起来吗?的主要内容,如果未能解决你的问题,请参考以下文章

MySql Group by 与 Pivot

SQL Pivot基于一列的Max

将 Total 列添加到 Dynamic SQL pivot

SQL中PIVOT 行列转换

POWER PIVOT基础篇

Saiku Analytics 与 Pivot4J