是否有一种简单的方法可以将具有父子关系的表迁移到第一列?
INPUT_TABLE
PARENT_ID,ID,NAME
null,1, USA
1 ,2, Las Vegas
2 ,3, City in las Vegas
2 ,4, Another City in las Vegas
.. a lot more
输出
ID, COUNTRY, CITY, PLACE
1, USA, null,null
2, USA, Las Vegas,null
3, USA, Las Vegas,City in las Vegas
4, USA, Las Vegas,Another City in las Vegas
提前致谢
答案 0 :(得分:1)
根据您的评论,如果你有3个项目的层级,并且不需要保留没有City
或Place
的行,那么将表连接两次就足够了。
SELECT ID = Country.ID
, Country = Country.NAME
, City = City.NAME
, Place = Place.Name
FROM q Country
INNER JOIN q City ON City.PARENT_ID = Country.ID
INNER JOIN q Place ON Place.PARENT_ID = City.ID
;WITH q (PARENT_ID, ID, NAME) AS (
SELECT null, 1, 'USA'
UNION ALL SELECT 1, 2, 'Las Vegas'
UNION ALL SELECT 2, 3, 'City in las Vegas'
UNION ALL SELECT 2, 4, 'Another City in las Vegas'
)
SELECT ID = Country.ID
, Country = Country.NAME
, City = City.NAME
, Place = Place.Name
FROM q Country
INNER JOIN q City ON City.PARENT_ID = Country.ID
INNER JOIN q Place ON Place.PARENT_ID = City.ID