2017-06-20 685 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 |