根据条件SQL Server中记录的可能组合

时间:2020-06-05 14:00:27

标签: sql sql-server

我的输入如下:

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

1 个答案:

答案 0 :(得分:1)

基本思想是枚举差异条件。一种技巧是分配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;

如果您的数据库不支持此确切语法,则它支持类似的内容。

Here是db <>小提琴。