0

I know the title is very vague but I didn't know how to explain this question better, if you have any suggestions please do tell me.

I have this table:

CRAccountID DBAccountID Value

And I want to have a row for each CRAccountID and DBAccountID for example:

CRAccountID DBAccountID Value
100          111         10

I want to get these records:

AccountID  Value
100         10
111        -10

If you haven't noticed yet I also want to make the DBAccountID value in minus.

I tried it by selecting both of them and doing a Union but it takes way too much time when the table gets bigger (the table can contain more than 4 million records)

Here's my code:

select CRAccountID as AccountID, Value from MyTable
UNION
select DBAccountID as AccountID, -Value as Value from MyTable

Note: my code is much much bigger than this with almost 4 joins in each union therefore it becomes so slow.

I'm using Microsoft SQL.

4
  • If you want every row then a full table scan is required so not sure if there is a quicker option, but are you just selecting specific transactions? Commented Mar 20, 2021 at 18:23
  • By transactions are you referring to records in this table? If so, no. I'm trying to get a report of all the data (using paging or such) Commented Mar 20, 2021 at 18:26
  • One small thing, if you use UNION ALL instead of UNION it doesn't do the step where it tries to de-dupe the result set. Commented Mar 20, 2021 at 18:32
  • Yeah, sorry, forgot that transaction is ambiguous in this context! I did mean every row, as each represents a debit/credit transaction. Good tip about union all, and I see you got a good answer - I didn't know about apply. Commented Mar 20, 2021 at 20:33

1 Answer 1

1

You want to unpivot the data. I would recommend apply:

select v.account, v.value
from t cross apply
     (values (t.CRAccountID, t.value),
             (t.DBAccountID, - t.value)
     ) v(account, value) ;

You can express your complex as a CTE or subquery. Or just include it in the query before the cross apply.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you so much! That's exactly what I needed.

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.