In MySQL können Sie die Funktion group_concat()
verwenden, um eine gruppierte Zeichenfolgenverkettung zu erreichen, und in HIVE SQL können Sie die Funktion concat_ws()+collect_set()/collect_list()
verwenden, um dies zu erreichen gleicher Effekt.
Beispiel:
A | B | C |
---|---|---|
2014 | B | 9 |
2015 | A | 8 |
2014 | A | 10 |
2015 | B | 7 |
2014 | B | 6 |
1.concat_ws+collect_list nicht dupliziertes Spleißen
select a
,concat_ws('-',collect_list(b)) as col_b
,concat_ws('-',collect_list(cast(c as string))) as col_c
from tb_name
group by a
;
Suchergebnis:
A | col_b | col_c |
---|---|---|
2014 | B-A-B | 9-10-6 |
2015 | A-B | 8-7 |
2.concat_ws+collect_set Deduplizierung und Spleißen
select a
,concat_ws('-',collect_set(b)) as col_b
,concat_ws('-',collect_set(cast(c as string))) as col_c
from tb_name
group by a
;
Suchergebnis:
A | col_b | col_c |
---|---|---|
2014 | B-A | 9-10-6 |
2015 | A-B | 8-7 |
3. Wenn Sie die Spleißergebnisse beim Gruppieren und Spleißen in Ordnung halten müssen, können Sie die folgenden zwei Methoden verwenden
1) Zuerst sortieren und dann spleißen
select a
,concat_ws('-',collect_set(b)) as col_b
,concat_ws('-',collect_set(cast(c as string))) as col_c
from
(
select a
,b
,c
,row_number() over (partition by a order by b asc) as rn
from tb_name
) t
group by a
;
Suchergebnis:
A | col_b | col_c |
---|---|---|
2014 | A-B | 10-6-9 |
2015 | A-B | 8-7 |
select a
,concat_ws('-',collect_list(b)) as col_b
,concat_ws('-',collect_list(cast(c as string))) as col_c
from
(
select a
,b
,c
,row_number() over (partition by a order by b asc) as rn
from tb_name
) t
group by a
;
Abfrageergebnisse: (Die Positionen von col_b und col_c stimmen überein und die Zeichen in col_b sind in der richtigen Reihenfolge)
A | col_b | col_c |
---|---|---|
2014 | A-B-B | 10-6-9 |
2015 | A-B | 8-7 |
2) Die Funktion sort_array() sortiert in aufsteigender Reihenfolge
select a
,concat_ws('-',sort_array(collect_list(b))) as col_b
from tb_name
group by a
;
A | col_b |
---|---|
2014 | A-B-B |
2015 | A-B |