[英]Possible combinations of records in sql server based on condition
我的輸入如下:
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
我的 Output 應該如下所示:(需要記錄的組合與 'P' 作為每個 c1,c2 的值)
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
基本思想是枚舉差異條件。 一個技巧是分配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;
如果您的數據庫不支持這種確切的語法,它支持類似的東西。
這是一個 db<>fiddle。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.