WeekNo Accounts Qty DisputeAmt RplyStatus
22 a 5 19.0 CREDIT
21 b 3 26.5 PARTIAL
22 a 6 12.5 NOT YET
22 b 1 26.5 PARTIAL
21 b 2 55.5 NOT YET
我要實現根據WeekNo和Accounts字段得到不同狀態RplyStatus水平排列,(其中SUBTOTAL是根據不同WeekNo和Accounts對每個不同狀態的DisputeAmt字段匯總) 要得到的結果如下:
WeekNo Accounts CREDIT SUBTOTAL PARTIAL SUBTOTAL NOT YET SUBTOTAL
21 b 0 0 3 26.5 2 55.5
22 a 5 19.0 1 26.5 6 12.5
22 b 0 0 1 26.5 0 0
謝謝 !
2 个解决方案
#1
declare @s varchar(8000)
set @s=''
select @s=@s+',['+RplyStatus+']=sum(case RplyStatus when '''+RplyStatus
+''' then Qty else 0 end),SUBTOTAL=sum(case RplyStatus when '''
+RplyStatus+''' then DisputeAmt else 0 end)'
from 表
group by RplyStatus
exec('select WeekNo,Accounts'+@s+'
from 表
group by WeekNo,Accounts')
set @s=''
select @s=@s+',['+RplyStatus+']=sum(case RplyStatus when '''+RplyStatus
+''' then Qty else 0 end),SUBTOTAL=sum(case RplyStatus when '''
+RplyStatus+''' then DisputeAmt else 0 end)'
from 表
group by RplyStatus
exec('select WeekNo,Accounts'+@s+'
from 表
group by WeekNo,Accounts')
#2
謝謝邹建,你的思路很清晰,SQL語句達到了我要實現的意圖!非常好!
#1
declare @s varchar(8000)
set @s=''
select @s=@s+',['+RplyStatus+']=sum(case RplyStatus when '''+RplyStatus
+''' then Qty else 0 end),SUBTOTAL=sum(case RplyStatus when '''
+RplyStatus+''' then DisputeAmt else 0 end)'
from 表
group by RplyStatus
exec('select WeekNo,Accounts'+@s+'
from 表
group by WeekNo,Accounts')
set @s=''
select @s=@s+',['+RplyStatus+']=sum(case RplyStatus when '''+RplyStatus
+''' then Qty else 0 end),SUBTOTAL=sum(case RplyStatus when '''
+RplyStatus+''' then DisputeAmt else 0 end)'
from 表
group by RplyStatus
exec('select WeekNo,Accounts'+@s+'
from 表
group by WeekNo,Accounts')
#2
謝謝邹建,你的思路很清晰,SQL語句達到了我要實現的意圖!非常好!