Nicolas
Nicolas

Reputation: 94

SQL, need to transform a table

I'm working with Microsoft SQL Server 2014. I have a table with next data format:

|customerId | action | amount | isSuccessful | paymentCount |
|____1____  |__ W__  |____10__|____0____     |_____2________|
|____1____  |__ D__  |____20__|____1____     |_____3________|
|____1____  |__ W__  |____30__|____1____     |_____1________|
|____1____  |__ D__  |____40__|____0____     |_____1________|

What I need is to do report with this format:

|customerId|depositAmount|withdrawalAmount|depositAttemptCount|withdrawalAttemptCount|
|____1____ |______20 ____|________30_____ |________4_______  _|________3__________ |

How it's possible to 'transform' table with select?

I would appreciate any help.

Upvotes: 0

Views: 44

Answers (1)

Gurwinder Singh
Gurwinder Singh

Reputation: 39537

You can use conditional aggregation here:

select customerId,
    sum(case when action = 'D' and isSuccessful = 1 then amount else 0 end) as depositAmount,
    sum(case when action = 'W' and isSuccessful = 1 then amount else 0 end) as withdrawalAmount,
    sum(case when action = 'D' then paymentCount else 0 end) as depositAttemptCount,
    sum(case when action = 'W' then paymentCount else 0 end) as withdrawalAttemptCount
from your_table
group by customerId;

Upvotes: 3

Related Questions