根据每种情况下的其他列生成一列

时间:2019-02-28 10:49:31

标签: sql teradata string-aggregation

输入:

| case_no | activity | country |
|---------|----------|---------|
|       1 | a1       | A       |
|       1 | a1       | A       |
|       1 | a1       | B       |
|       2 | a2       | C       |
|       2 | a2       | D       |
|       3 | a3       | E       |
|       3 | a3       | E       |

输出新列 case_countries

| case_no | activity | country | case_countries |
|---------|----------|---------|----------------|
|       1 | a1       | A       | A,B            |
|       1 | a1       | A       | A,B            |
|       1 | a1       | B       | A,B            |
|       2 | a2       | C       | C,D            |
|       2 | a2       | D       | C,D            |
|       3 | a3       | E       | E              |
|       3 | a3       | E       | E              |

我想生成 case_countries 列,以将每个活动的所有国家/地区保留在一个案例中。有什么建议么?

ps。我使用Teradata

1 个答案:

答案 0 :(得分:2)

在Teradata中,这不是真的很丑,但仍然更复杂:

SELECT
    t1.case_no,
    t1.activity,
    t1.country,
    t2.case_countries
FROM yourTable  t1
INNER JOIN
 (
   SELECT case_no, activity,
      Trim(Trailing ',' FROM XmlAgg(country||',' ORDER BY country) (VARCHAR(200))) AS case_countries
   FROM 
    (
      SELECT DISTINCT case_no, activity, country
      FROM yourTable
    ) t2
   GROUP BY 1,2 
 ) t2
ON t1.case_no = t2.case_no
AND t1.activity = t2.activity;