获取字段层次结构
Posted
技术标签:
【中文标题】获取字段层次结构【英文标题】:Get Field Hierachy 【发布时间】:2020-03-05 19:33:49 【问题描述】:我有以下表格,我想按国家/地区获取用户数量:
+--------+------+:
| user | zone |
+--------+------+
| Paul | 7 |
+--------+------+
| John | 5 |
+--------+------+
| Peter | 6 |
+--------+------+
| Frank | 5 |
+--------+------+
| Silvia | 2 |
+--------+------+
| Carl | 4 |
+--------+------+
| Mark | 3 |
+--------+------+
地区
+---------+-----------------+----------+--+
| zone_id | zone_name | idUpzone | |
+---------+-----------------+----------+--+
| 1 | Global | null | |
+---------+-----------------+----------+--+
| 2 | US | 1 | |
+---------+-----------------+----------+--+
| 3 | Florida | 2 | |
+---------+-----------------+----------+--+
| 4 | Orlando | 3 | |
+---------+-----------------+----------+--+
| 5 | China | 1 | |
+---------+-----------------+----------+--+
| 6 | Orlando Sector | 4 | |
+---------+-----------------+----------+--+
| 7 | Beijing | 5 | |
+---------+-----------------+----------+--+
所以我得到了这样的东西
+---------+-----+
| Country | QTY |
+---------+-----+
| US | 4 |
+---------+-----+
| China | 3 |
+---------+-----+
【问题讨论】:
听起来是递归 CTE 的好用例。 ***.com/questions/4048151/… 【参考方案1】:使用递归 CTE 获取***别,然后 join
:
with cte as (
select zone_id, zone_id as top_zone_id, zone_name as top_zone_name, 1 as lev
from regions
where parent_zone_id = 1
union all
select r.zone_id, cte.top_zone_id, top_zone_name, lev + 1
from cte join
regions r
on r.idUpzone = cte.zone_id
)
select cte.top_zone_name, count(*)
from users u join
cte
on u.zone = cte.zone_id
group by cte.top_zone_name;
【讨论】:
将parent_zone_id
替换为idUpzone
,这很好。而且...您在 CTE 的第二部分忘记了 top_zone_name
。【参考方案2】:
试试这个:
SELECT
r.zone_name AS Contry, COUNT(*) QTY
FROM (
SELECT * FROM users u
INNER JOIN regions r ON u.zone = r.zone_id
) a
GROUP BY r.zone_name
【讨论】:
这行不通,因为它是一个多层次的层次结构。以上是关于获取字段层次结构的主要内容,如果未能解决你的问题,请参考以下文章