[英]Group by and Join on same Table Sql - PostgreSql
I have a table like this:我有一张这样的桌子:
Id | Name | ParentId | Hierarchy
1 | California | 1 | 1
2 | San Deigo | 1 | 2
3 | Bay Area | 1 | 2
4 | San Fran | 1 | 2
Hierachy 1 indicates top level like California.层次 1 表示像加利福尼亚这样的顶级。 Hierarchy 2 indicate second level like state/region in California eg San Diego.
层次结构 2 表示第二级,例如加利福尼亚州/地区,例如圣地亚哥。 Hierarchy 3 indicates third level like street in San Diego.
层次结构 3 表示第三层,如圣地亚哥的街道。 Is it possible to get districts with parent codes with hierarchy 2. It looks like it needs group by and join in same table.
是否可以获得具有层次结构 2 的父代码的地区。看起来它需要分组并加入同一张表。
This answers the original version of the question.这回答了问题的原始版本。
Is it possible to get districts with parent codes with hierarchy 2?
是否有可能获得具有层次 2 的父代码的地区?
This is just a select:这只是一个 select:
select t.districtname, t.parencdoe
from t
where t.hierarhy = 2;
Your data is malformed.您的数据格式不正确。 You should have a parentid column that refers to the primary key of the table.
您应该有一个parentid列引用表的主键。 The
parentcode
is not appropriate. parentcode
不合适。 It also seems redundant to have columns like regionname
in all rows.在所有行中都有像
regionname
这样的列似乎也是多余的。
I have comeup with the following solution:我想出了以下解决方案:
select p.name as Parent,
c.name as Child
FROM
theTable p
INNER JOIN theTable c ON p.id = c.parentId
where p.hierarchy = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.