获取字段层次结构

Get Field Hierachy

我有下表,我想按国家/地区获取用户数量:

+--------+------+:
| 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得到最高级别然后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;

试试这个:

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