我可以在 Microsoft SQL Server 中将 PIVOT 与内部联接结合起来吗?
我有以下 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 LifeExpTotal
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
Mexico 1567000000000000 1.3
United States 14440000000000000 0.4
另请注意,我在两个表中都有 CountryID,它们指的是同一个国家/地区。我想要的是创建一个 SQL 查询,可能使用 INNER JOIN,返回以下内容:
CountryName CountryGDP CountryGDPGrowth CountryGDPPerCapita LifeExpTot
al Mexico 156700000000000000 1.3 35985.78 77.24
United States 144400000000000000 0.4 9147.7 74.54
帮我做这个查询吗?或者告诉我是否可能?
I have the following SQL query:
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
This returns something that looks like this:
CountryID CountryGDPPerCapita LifeExpTotal
3 35985.78 77.24
5 9147.7 74.54
Then I have another query as follows:
SELECT CountryName, CountryGDP, CountryGDPGrowth
FROM globaledge.dbo.Country_Statistics
WHERE CountryID IN (3,5)
AND year=2002
Order By CountryName
Which produces the following:
CountryName CountryGDP CountryGDPGrowth
Mexico 1567000000000000 1.3
United States 14440000000000000 0.4
Also note, I do have CountryID in both tables, that refer to the same country. What I want is to create one SQL Query, maybe with an INNER JOIN, that would return the following:
CountryName CountryGDP CountryGDPGrowth CountryGDPPerCapita LifeExpTotal
Mexico 156700000000000000 1.3 35985.78 77.24
United States 144400000000000000 0.4 9147.7 74.54
Could anyone help me make this query? or tell me if it's possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的事情会起作用:
Something like this would work: