跨越多行的子字符串的最小值 - 排除空白并获取最小值

时间:2017-11-28 18:50:46

标签: mysql sql substring s

我这里有一个示例数据: 我需要的是每个product_id,每个级别的最小数量

预期结果

= 10093    3    183   184   185

但由于我有相同产品ID的多行,因此在第4级中选择空白超过184

Click here for example dataset- Product in different levels

select 
cc.product_id,
substring_index(substring_index(concat(cc.path, '/////'), '/', 2), '/', -1) as level_2,   
substring_index(substring_index(concat(cc.path, '/////'), '/', 3), '/', -1) as level_3,   
substring_index(substring_index(concat(cc.path, '/////'), '/', 4), '/', -1) as level_4,
substring_index(substring_index(concat(cc.path, '/////'), '/', 5), '/', -1) as level_5

from 
cc

1 个答案:

答案 0 :(得分:0)

您可以在汇总时使用case来过滤掉0值:

select product_id,
       min(case when level_2 + 0 > 0 then level_2 + 0 end) as min_level_2,
       min(case when level_3 + 0 > 0 then level_3 + 0 end) as min_level_3,
       min(case when level_4 + 0 > 0 then level_4 + 0 end) as min_level_4,
       min(case when level_5 + 0 > 0 then level_5 + 0 end) as min_level_5
from (select cc.product_id,
             substring_index(substring_index(concat(cc.path, '/////'), '/', 2), '/', -1) as level_2,   
             substring_index(substring_index(concat(cc.path, '/////'), '/', 3), '/', -1) as level_3,   
             substring_index(substring_index(concat(cc.path, '/////'), '/', 4), '/', -1) as level_4,
             substring_index(substring_index(concat(cc.path, '/////'), '/', 5), '/', -1) as level_5
      from cc
     ) cc
group by product_id;

注意:您也可以将条件写为when level_2 <> ''