2017-04-01 54 views
0

我与Microsoft SQL Server 2014的工作我 有下一个数据格式的表格:SQL,需要改造的表

|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“转换”表?

我将不胜感激任何帮助。

+0

看一看这里: http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql -server – IngoB

回答

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; 
+0

这是正确的解决方案!非常感谢你! – Nicolas