T SQL:子选择查询中的内连接?

时间:2015-01-28 11:46:09

标签: sql sql-server join

我是WPF开发人员而不是sql dba ...尝试在子选择中进行连接。 我有两张桌子:tbArticles& tbRegions。 TbArticles拥有regionCode列,这也是tbRegions的常用列。我试图按地区和国家统计所有文章:

enter image description here

enter image description here

这是我正在寻找的结果:

enter image description here

我设法通过内部联盟从区域获得国家:

select distinct r.longName, a.Country
from ises.tbarticles a
INNER JOIN ref.tbRegions r
On a.RegionCode = r.regionCode
order by longName

但是如何通过连接作为子选择获得我想要的结果?我尝试过这种事情,但显然它不对。

select (select distinct r.longName from ises.tbarticles a
INNER JOIN ref.tbRegions r
on r.regionCode = a.RegionCode) as 'Region', country, COUNT(*) as 'Total Articles' from ises.tbarticles a, ref.tbRegions r
group by country
order by Region

3 个答案:

答案 0 :(得分:1)

试试这个:

select r.longName, a.Country, count(*)
from ises.tbarticles a
INNER JOIN ref.tbRegions r
On a.RegionCode = r.regionCode
group by  r.longName, a.Country
order by longName

答案 1 :(得分:1)

使用需要使用GROUP BY Clause然后使用计数

Select r.longName, a.Country, Count(a.*) as ArticleCount
From ises.tbarticles a 
     INNER JOIN ref.tbRegions r On a.RegionCode = r.regionCode
Group By r.longName, a.Country

答案 2 :(得分:1)

试试这个:

DECLARE @TbArticles TABLE(regionCode INT, Coutry NVARCHAR(MAX), Body NVARCHAR(MAX))
DECLARE @TbRegions TABLE(regionCode INT, Name NVARCHAR(MAX))

INSERT INTO @TbArticles VALUES
(10, N'Australia', 'blah'),
(10, N'Fiji', 'blah'),
(12, N'USA', 'blah'),
(15, N'Belgium', 'blah')


INSERT INTO @TbRegions VALUES
(10, N'Australia'),
(12, N'North America'),
(15, N'Western Europe')



SELECT r.Name, a.Coutry, COUNT(*) AS ArticleCount FROM @TbArticles a
JOIN @TbRegions r ON r.regionCode = a.regionCode
GROUP BY r.regionCode, r.Name, a.Coutry

输出:

Name            Coutry      ArticleCount
Australia       Australia   1
Australia       Fiji        1
North America   USA         1
Western Europe  Belgium     1