簡體   English   中英

如何根據字符串聚合列從另一個表中添加項目

[英]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

接下來我可以嘗試什么?

嘗試以下操作:

select t1.cust_id
    , t1.tran
    , t1.item
    , sum(t2.value) as target
from table_1 t1
    , UNNEST(split(t1.item ,',')) as item_unnested
LEFT JOIN table_2 t2
 on item_unnested=t2.item
group by t1.cust_id
    , t1.tran
    , t1.item

使用您的數據,它提供以下信息:

在此處輸入圖像描述

創建一個中心表,將項目列值拆分為行並將該表與 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

考慮以下簡單的方法

select *, 
  ( select sum(value)
    from unnest(split(item)) item
    join table2 
    using (item)
  ) target
from table1             

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM