gpt4 book ai didi

sql - 如何知道区域表中的父区域级别名称?

转载 作者:行者123 更新时间:2023-12-04 23:52:23 24 4
gpt4 key购买 nike

我创建了这张表

CREATE TABLE Region
(
RegionID INT PRIMARY KEY ,
ParentRegionID INT FOREIGN KEY REFERENCES dbo.Region,
RegionName NVARCHAR(30)
);

我插入一些这样的值:
    INSERT  INTO dbo.Region
( RegionID, ParentRegionID, RegionName )
VALUES ( 1, NULL, N'USA' ),
( 2, 1, N'California' ),
( 3, 2, N'Los Angeles' ),
( 4, 2, N'California City' ),
( 5, 2, N'San Diego' ),
( 6, 2, N'Bakersfield' ),
( 7, 1, N'Alaska' ),
( 8, 7, N'Wrangell' ),
( 9, 7, N'Anchorage' ),
( 10, 7, N'Juneau' );

我希望我的查询返回

ParentRegionID RegionID RegionName RegionLevelName
NULL           1            USA            Country
1 2 California State
1 7 Alaska State
7 8 Wrangell City
7 9 Anchorage City
7 10 Juneau City
2 3 Los Angeles City
2 4 CaliforniaCity City
2 5 San Diego City
2 6 Bakersfield City

最佳答案

试试这个代码

WITH    RegionTree ( ParentRegionID, RegionID, RegionName, RegionLevel )
AS (
SELECT ParentRegionID ,
RegionID ,
RegionName ,
0 AS RegionLevel
FROM Region
WHERE ParentRegionID IS NULL
UNION ALL
SELECT c.ParentRegionID ,
c.RegionID ,
c.RegionName ,
p.RegionLevel + 1
FROM Region c
INNER JOIN RegionTree p ON c.ParentRegionID = p.RegionID
)
SELECT ParentRegionID ,
RegionID ,
RegionName ,
CASE WHEN RegionLevel = 0 THEN 'Country'
WHEN RegionLevel = 1 THEN 'State'
WHEN RegionLevel = 2 THEN 'City'
END AS RegionLevelName
FROM RegionTree;

关于sql - 如何知道区域表中的父区域级别名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com