带编号的多表 CTE

问题描述

我正在为我拥有的数据库使用通用表表达式 (CTE)。

tbldistricts 地区 ID (pk) 区

tblVillage 村庄 ID (pk) 区号 村庄

tblWard 病房 ID (pk) 村号 区号 村庄

下面是如何创建示例数据库

Create Table tbldistricts(
    [districtID] [int] IDENTITY(1,1) NOT NULL Primary Key Clustered,[district] [nvarchar](200) NOT NULL
)


GO
Create Table tblVillage(
    [VillageID] [int] IDENTITY(1,[districtID] [int] NOT NULL,[Village] [nvarchar](200) NOT NULL
)

GO
Create Table tblWards(
    [WardID] [int] IDENTITY(1,[VillageID] [int] NOT NULL,[Ward] [nvarchar](200) NOT NULL
)

GO

Insert into tbldistricts Values ('Barolong')
Insert into tbldistricts Values ('Central_Bobonong')
Insert into tbldistricts Values ('Central_Boteti')
Insert into tbldistricts Values ('Central_Mahalapye')
Insert into tbldistricts Values ('Central_Tutume')
Insert into tbldistricts Values ('Chobe')
GO

Insert into tblVillage Values (1,'Bethel')
Insert into tblVillage Values (1,'Borobadilepe')
Insert into tblVillage Values (1,'Digawana')
Insert into tblVillage Values (1,'Dikhukhung')
Insert into tblVillage Values (1,'Dinatshana')

GO

Insert into tblVillage Values (2,'Bobonong')
Insert into tblVillage Values (2,'damochojena')
Insert into tblVillage Values (2,'Kobojango')
GO

Insert into tblVillage Values (5,'Shakwe')
Insert into tblVillage Values (5,'Shoshong')
Insert into tblVillage Values (5,'Taupye')
Insert into tblVillage Values (5,'Tewane')
GO


Insert into tblWards Values (1,3,'Shakwe')
Insert into tblWards Values (1,'Shoshong')
Insert into tblWards Values (2,6,'Taupye')
Insert into tblWards Values (2,8,'Tewane')
Insert into tblWards Values (5,9,'Shakwe')

GO

我想要一个看起来像这样的输出,但不确定 CTE 是否是唯一的选择:

| ID| ParéntID | Item       | districtID | VillageID | WardID |

| 1 | 0        | district 1 |1           |0           |0      |
| 2 | 1        | Village  1 |1           |1           |0      |
| 3 | 1        | Village  2 |1           |2           |0      |
| 4 | 2        | Ward 1     |1           |1           |1      |
| 5 | 0        | district 2 |2           |0           |0      |
| 6 | 5        | Village 3  |2           |3           |0      |
| 7 | 6        | Ward     2 |2           |3           |2      |

我希望我已经为我的问题提供了足够的信息。

KK

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)