[英]How to add items from another table based on a string aggregated column
我有兩張這樣的桌子
[表格1]:
|cust_id| tran |item |
| ------| -----|-------
| id1 | 123 |a,b,c |
| id2 | 234 |b,b |
| id3 | 345 |c,d,a,b|
[表2]:
| item. | value |
| ----- | ----- |
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
我想通過使用大查詢從表 1 中的表 2 進行查找來創建目標值。
|cust_id| tran.|item |target|
| ------| -----|------|------|
| id1 | 123 |a,b,c | 6
| id2 | 234 |b,b | 4
| id3 | 345 |c,d,a,b| 10
接下來我可以嘗試什么?
創建一個中心表,將項目列值拆分為行並將該表與 table2 連接。 嘗試關注
--Cursor is used to split the item data row by row
--#temp is a temporary table
create table #temp (id varchar(10), trans varchar(10), item varchar(10), item1 varchar(10));
DECLARE @item varchar(10);
DECLARE @id varchar(10);
DECLARE @trans varchar(10);
DECLARE item_cusor CURSOR FOR
SELECT *
FROM table1;
OPEN item_cusor
FETCH NEXT FROM item_cusor
INTO @id,@trans,@item
WHILE @@FETCH_STATUS = 0
BEGIN
insert into #temp
SELECT @id,@trans,@item,*
FROM STRING_SPLIT (@item, ',')
FETCH NEXT FROM item_cusor
INTO @id,@trans,@item
END
CLOSE item_cusor;
DEALLOCATE item_cusor;
--select * from temp
select t.id as cust_id, t.trans,t.item , sum(cast(t2.value as int)) as target
from #temp t
JOIN table2 t2
on t.item1=t2.item
group by t.id, t.trans,t.item;
光標: https://www.c-sharpcorner.com/article/cursors-in-sql-server/
臨時表: https://www.sqlservertutorial.net/sql-server-basics/sql-server-temporary-tables/
字符串拆分 function: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.