0

I wish to make my data from :-

Customer Product TransactionType Quantity Value
  A       ItemA        Sale         1      10
  A       ItemA        Refund       1      10
  C       ItemB        Sale         1       5

To following structure:-

Customer Product SaleValue SaleQuantity RefundValue RefundQuantity 
   A      ItemA        10          1           10           1
   C      ItemB         5          1            0           0

I just want to make TransactionType & Quantity in order to split into individual txn type column & its own quantity. I tried to use MSSQL Pivot function, but it does not suit my need. I don't expect full answer, but at least I need some ideas on this. Thanks.

1
  • Do a GROUP BY. Use case expressions to do conditional aggregation. Commented Mar 4, 2020 at 9:47

2 Answers 2

1

You can do aggregation :

select customer, product, 
       sum(case when transactiontype = 'sale' then value else 0 end) as salevalue,
       sum(case when transactiontype = 'sale' then Quantity else 0 end) as saleqty,
       sum(case when transactiontype = 'Refund' then value else 0 end) as Refundvalue,
       sum(case when transactiontype = 'Refund' then Quantity else 0 end) as Refundqty
from table t
group by customer, product
Sign up to request clarification or add additional context in comments.

Comments

0

Use pivoting logic:

SELECT
    Customer,
    Product,
    MAX(CASE WHEN TransactionType = 'Sale'   THEN Value END) AS SaleValue,
    MAX(CASE WHEN TransactionType = 'Sale'   THEN Quantity END) AS SaleQuantity,
    MAX(CASE WHEN TransactionType = 'Refund' THEN Value END) AS RefundValue,
    MAX(CASE WHEN TransactionType = 'Refund' THEN Quantity END) AS RefundQuantity
FROM yourTable
GROUP BY
    Customer,
    Product;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.