Вы можете использовать условное агрегирование. Ваше sum()
выражение длинное, поэтому я бы добавил один уровень агрегации, чтобы не повторять его много раз:
select
ItcodedGrp,
ItheadCat,
ItheadCls,
ItheadGrp,
sum(AllStock) AllStock,
sum(case when POSid = 2 then AllStock end) POSid2,
sum(case when POSid = 6 then AllStock end) POSid6,
sum(case when POSid = 7 then AllStock end) POSid7,
sum(case when POSid = 10 then AllStock end) POSid10,
sum(case when POSid = 11 then AllStock end) POSid11,
sum(case when POSid = 12 then AllStock end) POSid12,
sum(case when POSid = 13 then AllStock end) POSid13,
sum(case when POSid = 14 then AllStock end) POSid14
from (
select
ItcodedGrp,
ItheadCat,
ItheadCls,
ItheadGrp,
POsid,
(
sum(OpnQty)
+ sum(FaultyQty)
+ sum(UsedQty)
+ sum(RecQty)
- sum(RejectQty)
- sum(Issued)
+ sum(DebitQty)
+ sum(AdjQty)
+ sum(STNQtyPls)
- sum(STNQtyMin)
- sum(POSQTY)
- sum(TransitQty)
- sum(FQtyMin)
+ sum(FQtyPlus)
+ sum(ReplaceQty)
) as AllStock
from Vmgt_RSales_Stock
where
POsid in (2,6,7,10,11,12,13,14)
and ItcodedGrp like '28.01.059.%'
group by
ItcodedGrp,
ItheadCat,
ItheadCls,
ItheadGrp,
POsid
) t
group by
tcodedGrp,
ItheadCat,
ItheadCls,
ItheadGrp