SQL,需要转换表

时间:2017-04-01 19:40:31

标签: sql sql-server

我正在使用Microsoft SQL Server 2014。 我有一个下一个数据格式的表:

|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________|

我需要的是用这种格式报告:

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

如何用select?'/ p>'转换'表

我将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以在此处使用条件聚合:

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;