1

假设我有一个名为和cities字段的表。数据如下所示:statecity

State     City
Ohio      Eaton
Ohio      Columbus
Ohio      Dayton
Ohio      Greenville
New York  New York
New York  Albany
New York  Syracuse

我希望能够做到这一点:

select state, join(city,',') from cities
group by state

...返回这个:

State     City
Ohio      Eaton,Columbus,Dayton,Greenville
New York  New York,Albany,Syracuse

我需要为此创建一些疯狂的 UDF 吗?如果没有函数,有没有办法应用一些 SQL 魔法来实现这一点?

4

1 回答 1

2

递归 CTE 应该能够做到这一点。我模拟了要为每个状态重置的序列号。您可能需要根据您的实际表格进行调整,但它至少应该让您思考正确的方向。(类似于 Marc B 在 Teradata 论坛上链接的内容,但希望这更容易阅读。)

WITH RECURSIVE city_list (state, cities, seq) AS
(
  SELECT s.state
       , s.city
       , ROW_NUMBER() OVER (PARTITION BY State ORDER BY State, City) AS seq
  FROM   states s
  QUALIFY  seq = 1
  UNION ALL
  SELECT c.cities ||’, ’|| s.city
       , ROW_NUMBER() OVER (ORDER BY State, City) AS seq
  FROM   city_list c, states s
  WHERE  s.seq = c.seq + 1
    AND  s.state = c.state
)
SELECT r.state, r.cities
FROM   city_list r
WHERE  r.seq = (SELECT MAX(h.seq) FROM city_list h 
                WHERE h.state = r.state 
                GROUP BY h.state)
;
于 2013-04-11T23:32:24.770 回答