2017-03-03 59 views
0

我有一个表,看起来像如下:创建指望表是引用自身

Table Image

下表列出的国家和地区(州,省,县等),在这些国家内。我需要计算所有国家内所有地区的数量。正如你所看到的,每个地区都有一个ParentID这是你可以在其中找到该地区的国家的ID。例如,加利福尼亚州位于美国,因此其母公司ID为1(美国的ID)。

所以,从简单的表上述结果应该是:

美国:2加拿大:1

我曾尝试以下:

  1. 全选值转换成表格,其中ID a 1(对于美国)
  2. 将所有值其中有一个表ID 3(加拿大)
  3. Parent ID为1
  4. Parent ID为3
  5. 做两个表计数选择所有的值到加拿大表中选择所有的值到美国表

上述方法的问题是,如果添加新国家,则不会自动生成计数。 任何想法使这更动态?

+0

表中有多少层嵌套? –

+0

只是2:国家和地区 – DanSm

回答

0

你必须加入该表本身:

select t1.ID, t1.segment, count(distinct t2.ID) 
from yourTable t1 
join yourTable t2 
on  t1.ID = t2.parentID 
where t1.parentID is null 
group by t1.ID, t1.segment 

where子句确保你只有“顶级”行会显示出来。

+0

谢谢@Stefano Zanini,但这只给予顶级行数。我想要顶级+子级别 – DanSm

+1

您的问题指出“我需要产生所有国家内所有地区的计数”,这很有意义,因为如果这些级别只是国家和地区,那么地区级计数将始终为1. 如果您想要显示区域级计数,则只需删除where子句即可。 –

0
CREATE TABLE CountriesRegions 
(
    [ID] [int] NOT NULL, 
    parentid [int] NULL, 
    segment [nvarchar](50) NULL) 

insert into CountriesRegions values (1,null,'usa'), (2,1, 'california'), (3, null, 'canada'), (4, 3, 'quebec'), (5, 1, 'NY') 

select a.id, a.segment, count(*) as [Region Count] 
from CountriesRegions a 
left join CountriesRegions b 
on a.id=b.parentid 
where b.id is not null 
group by a.id, a.segment 
+0

我认为(1,1,'usa')应该是(1,null,'usa')以匹配OP的表格。但是我不能提交这么小的编辑(少于6个字符的变化)。 – Degan

+0

@Degan谢谢。我已经做了这个改变。 – cloudsafe

0

也许重新格式化数据是有意义的,因为除了计算国家和地区之外,还有其他种类的查询。

CREATE TABLE #CountriesRegions 
(
    [ID] [int] NOT NULL, 
    parentid [int] NULL, 
    segment [nvarchar](50) NULL) 

insert into #CountriesRegions values (1,null,'usa'), (2,1, 'california'), (3, null, 'canada'), (4, 3, 'quebec'), (5, 1, 'NY') 

select * from #CountriesRegions 

Create table #Country 
([ID] [int] NOT NULL 
,[country_name] [nvarchar](50) NOT NULL) 

Insert into #Country select ID, segment AS country_name from #CountriesRegions where parentid IS NULL 

select * from #Country 

Create table #Region 
([ID] [int] NOT NULL 
,[country_id] [int] NOT NULL 
,[region_name] [nvarchar](50) NOT NULL) 

Insert into #Region select ID, parentid AS country_ID, segment AS region_name from #CountriesRegions where parentid IS NOT NULL 

select * from #Region 

Select COUNT(*) As 'Num of Countries' from #Country 
Select COUNT(*) As 'Num of Regions' from #Region