2017-06-20 691 views
0

我的下表中的标签列以逗号分隔,我需要将其分割为不同的行,如下所示。我在论坛上看到了多个链接,但大多数功能组合在SAP HANA中不起作用。任何帮助将不胜感激。将逗号分隔列拆分为SAP HANA中不同的行

MY_TABLE:

+-----+--------------+------------+-------------+ 
| id | parent_title | account_id | tags  | 
+-----+--------------+------------+-------------+ 
| 647 | title999  |   64 | 361,381,388 | 
| 646 | title998  |   64 | 361,376,388 | 
+-----+--------------+------------+-------------+ 

Required_Table

+-----+--------------+------------+------+ 
| id | parent_title | account_id | tags | 
+-----+--------------+------------+------+ 
| 647 | title999  |   64 | 361 | 
| 647 | title999  |   64 | 381 | 
| 647 | title999  |   64 | 388 | 
| 646 | title998  |   64 | 361 | 
| 646 | title998  |   64 | 376 | 
| 646 | title998  |   64 | 388 | 
+-----+--------------+------------+------+ 
+1

坦率地说,如果您想将标签作为单独的元素处理,请不要将它们存储在逗号分隔的列表中。就这么简单。这是最基本的关系数据库设计。 –

+0

是的@BillKarwin你是对的,但在这里的数据已经存储,我找不到一个方法,使其正确 –

+0

重复的https://stackoverflow.com/questions/44110999/how-to-split-multiple -values-from-a-row-into-separate-rows/44113101#44113101。检查我的答案。 –

回答

0

这将工作,需要创建2的临时表。作为比尔建议单独存储价值总是一个好主意。我假设你有3个数字后面跟着昏迷字符串并编译了这段代码。这将适用于您提供的样本数据。

create table #temp 
(id int, parent_title varchar(100), account_id int, tags varchar(max)) 
insert into #temp 
values ('647','title999','64', '361,381,388'); 

insert into #temp 
values ('647','title999','64', '361,376,388'); 

create table #temp2 
(id int, parent_title varchar(100), account_id int, tags varchar(max)); 


insert #temp2 (id,parent_title,account_id,tags) 
select id, parent_title,account_id, LEFT(tags,3) tags from #temp; 

insert #temp2 (id,parent_title,account_id,tags) 
select id, parent_title,account_id, right (tags,3) tags from #temp ; 


insert #temp2 (id,parent_title,account_id,tags) 
select id, parent_title,account_id, left(substring(tags,5,6),3) tags from #temp ; 

select * from #temp2 

drop table #temp ; 
drop table #temp2 
+0

标签数量和数字没有限制 –

0

尝试

SELECT id, parent_title, account_id, STRING_AGG(tags,',' ORDER BY tags) AS tags 
from your_Table 
group by id, parent_title, account_id 
order by 1 desc 

结果

| ID | parent_title | account_id |标签|

| 647 | title999 | 64 | 361,381,388 |

| 646 | title998 | 64 | 361,376,388 |