基于条件的sql server中记录的可能组合

wnavrhmk  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(296)

我的意见如下:

c1    c2      req         qty
1      A1     234         34
1      A1     547         45
1      A1     12P7        0.25
1      A1     12P8        0.25
1      A1     12P9        0.25

我的输出应该是这样的:(需要一个记录的组合,每个c1,c2的值都是'p')

c1    c2      c3    req         qty
1      A1      1    234         34
1      A1      1    547         45
1      A1      1    12P7        0.75

1      A1      2    234         34
1      A1      2    547         45
1      A1      2    12P8        0.75

1      A1      3    234         34
1      A1      3    547         45
1      A1      3    12P7        0.375
1      A1      3    12P8        0.375

1      A1      4    234         34
1      A1      4    547         45
1      A1      4    12P7        0.375
1      A1      4    12P9        0.375

1      A1      5    234         34
1      A1      5    547         45
1      A1      5    12P8        0.375
1      A1      5    12P9        0.375
xbp102n0

xbp102n01#

基本思想是列举不同的条件。一个窍门是分配 req . 这是通过计算总数并除以组中的行数来处理的:

select t.c1, t.c2, v.c3, t.req,
       (case when t.req like '12%'
             then (qty_total /
                   sum(case when t.req like '12%' then 1 else 0 end) over (partition by v.c3)
                  )
             else qty
        end)
from (select t.*, sum(case when req like '12%' then qty end) over () as qty_total
      from t 
     ) t cross join
     (values (1), (2), (3), (4), (5)) v(c3)
where t.req not like '12%' or
      (v.c3 = 1 and t.req in ('12P7') or
       v.c3 = 2 and t.req in ('12P8') or
       v.c3 = 3 and t.req in ('12P7', '12P8') or
       v.c3 = 4 and t.req in ('12P7', '12P9') or
       v.c3 = 5 and t.req in ('12P8', '12P9') 
      )
order by c3, c1, c2;

如果您的数据库不支持这种确切的语法,那么它也支持类似的语法。
这是一把小提琴。

相关问题