代码之家  ›  专栏  ›  技术社区  ›  Victor Wong

如何迭代列A以有条件地对列B求和?

  •  0
  • Victor Wong  · 技术社区  · 1 月前

    鉴于这张原始表格 Record :

    food   | food_preference | count
    --------------------------------
    burger | [burger]        | 100
    burger | [burger, pizza] | 70
    pizza  | [burger, pizza] | 130
    burger | [burger, corn]  | 25
    corn   | [burger, corn]  | 25
    

    我如何迭代所有独特的 food 将以下值相加 食物 在里面 food_preference 给予:

    food   | count
    --------------
    burger | 350
    pizza  | 200
    corn   | 50
    

    我尝试进行病例匹配,但不确定如何迭代食物价值。

    WITH Record AS
    (
        SELECT * FROM (
            values 
                ('burger', '[burger]', 100), 
                ('burger', '[burger, pizza]', 70), 
                ('pizza', '[burger, pizza]', 130), 
                ('burger', '[burger, corn]', 25), 
                ('corn', '[burger, corn]', 25)
        ) x(food, food_preference, count)
    )
    
    SELECT 
        food,
        CASE
            -- How to sum the count value if the food is in the food_preference? 
        END AS total_count
    FROM Record
    
    1 回复  |  直到 1 月前
        1
  •  1
  •   Caleb Carl    1 月前

    使用 STRING_SPLIT 会做你想做的事。

    SELECT value AS food
         , SUM(x.count) AS count
    FROM record AS x
        CROSS APPLY string_split(REPLACE(REPLACE(x.food_preference, '[', ''), ']', ''), ',') AS z
    GROUP BY value;
    

    DBFiddle