I have table
PONumber------ChargeAmount----Type
ABC123-----------1000---------------Freight
ABC123------------500----------------Freight
ABC123------------200----------------Miscellaneous
ABC123------------100----------------Miscellaneous
need output in record to be inserted into another table, Type - Freight should be added up to charges and type -Miscellaneous should be added to AdditionalCharges and AdditionalChargetype.
now if you have any other type other than Miscellaneous and Freight then you will need something different but with just those 2 here is one way of doing it
;with src
as
(
select PONumber,
sum(ChargeAmount) as AdditionalCharge,
Type as AdditionalChargeType
From @sample
where [Type] = 'Miscellaneous'
group by PONumber, Type
)
select s.PONumber,
sum(ChargeAmount) as Charge,
AdditionalCharge,
AdditionalChargeType
From @sample s
join src on s.PONumber = src.PONumber
where [Type] = 'Freight'
group by s.PONumber, AdditionalCharge, AdditionalChargeType
SELECT
PONumber,
SUM(CASE WHEN Type <> 'Miscellaneous' THEN ChargeAmount ELSE 0 END) AS Charge,
SUM(CASE WHEN Type = 'Miscellaneous' THEN ChargeAmount ELSE 0 END) AS AdditionalCharge,
'Miscellaneous' AS AdditionalChargeType
FROM @sample
GROUP BY PONumber
ORDER BY PONumber