简体   繁体   English

SQL,需要转换表

[英]SQL, need to transform a table

I'm working with Microsoft SQL Server 2014. I have a table with next data format: 我正在使用Microsoft SQL Server2014。我有一个具有下一个数据格式的表:

|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? 如何使用select来“转换”表?

I would appreciate any help. 我将不胜感激任何帮助。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM