SQL Server Lookup comma separated values in a column of a table in SQL or ADF

dluptydi  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(122)

I have three tables as below.

Main table:

Category look up table:

Seller lookup table:

Now I want to represent my data as below

What will the easiest way to do it in a SQL select statement? I would probably like to avoid any cursor or temp tables but rather using string_arg , cross apply , string split kind of functions to do it within select (if possible which I tried but could not arrive to a final solution ). I can also use ADF dataflow if needed.

khbbv19g

khbbv19g1#

Can't comment this, so here it is in answer format. This is just an example of one way to do so using outer apply. You'll have to do something similar for each table. I hope you can take it from here?

This does not address obvious design flaws in your data structure.

IF OBJECT_ID('Tempdb..#this') IS NOT NULL DROP TABLE #this;
IF OBJECT_ID('Tempdb..#Category') IS NOT NULL DROP TABLE #Category;
IF OBJECT_ID('Tempdb..#Seller') IS NOT NULL DROP TABLE #Seller;

CREATE TABLE #Category
    (
        CategoryID int
        , CategoryName varchar(75)
    )
;

INSERT INTO #Category
    (
        CategoryID
        , CategoryName
    )
VALUES
    (12, 'grocery'),
    (13, 'books'),
    (14, 'household')
;

CREATE TABLE #Seller
    (
        SellerID int
        , SellerName varchar(75)
    )
;

INSERT INTO #Seller
    (
        SellerID
        , SellerName
    )
VALUES
    (20, 'Amazon'),
    (21, 'starwar'),
    (23, 'Amway')
;

CREATE TABLE #this
    (
        id int
        , categoryid varchar(75)
        , sellerid varchar(75)
    )
;
INSERT INTO #this 
    (
        id
        , categoryid
        , sellerid
    )
VALUES
    (1, NULL, '20,23'),
    (2, '12,13,14', NULL),
    (3, '13', '21')
;

SELECT
    MainMapping.ID
    , STRING_AGG(c.CategoryName, ',') AS Categories
    , STRING_AGG(s.SellerName, ',') AS Sellers
FROM
    (
        SELECT 
            t.id
            , x.value AS SellerID
            , y.value AS CategoryID
        FROM 
            #this t
            OUTER APPLY string_split(sellerid, ',') x
            OUTER APPLY string_split(categoryid, ',') y
    ) MainMapping
    LEFT JOIN #Category c ON MainMapping.CategoryID = c.CategoryID
    LEFT JOIN #Seller s ON MainMapping.SellerID = s.SellerID
GROUP BY
    MainMapping.ID
;

IF OBJECT_ID('Tempdb..#this') IS NOT NULL DROP TABLE #this;
IF OBJECT_ID('Tempdb..#Category') IS NOT NULL DROP TABLE #Category;
IF OBJECT_ID('Tempdb..#Seller') IS NOT NULL DROP TABLE #Seller;

相关问题