0
我有兩個tabels:求和使用金額的情況下
MonthlySalary]:
MS_EmployeeID MS_Semel MS_Month MS_Amount
22222 9 1 4000
22222 9 2 4000
22222 9 3 4000
22222 9 4 5000
22222 9 5 5000
22222 9 6 3000
22222 9 7 2000
22222 9 8 5000
MSVTransaction:
MSV_EntitledIdNumber MSV_PaymentAmount MSV_Month
22222 3000 1
22222 3000 2
22222 4000 3
22222 5000 4
22222 6000 6
22222 7000 7
22222 2000 8
22222 5000 9
而且我試圖建立一個比較表。輸出應該是這樣的:
MSV_EntitledIdNumber MS_Semel Jan_MSV Jan_SML .... Aug_MSV Aug_SML
22222 9 3000 4000 5000 5000
我開始寫這篇:
select
distinct [MSV_EntitledIdNumber],
[MS_Semel],
sum(case when [MSV_Month] in (1) then [MSV_PaymentAmount] else 0 end) as JanMSV,
sum(case when [MS_Month] in (1) then [MS_Amount] else 0 end) as JanSML,
sum(case when [MSV_Month] in (2) then [MSV_PaymentAmount] else 0 end) as FebMSV,
sum(case when [MS_Month] in (2) then [MS_Amount] else 0 end) as FebSML,
sum(case when [MSV_Month] in (3) then [MSV_PaymentAmount] else 0 end) as MarMSV,
sum(case when [MS_Month] in (3) then [MS_Amount] else 0 end) as MarSML,
sum(case when [MSV_Month] in (4) then [MSV_PaymentAmount] else 0 end) as AprMSV,
sum(case when [MS_Month] in (4) then [MS_Amount] else 0 end) as AprSML,
sum(case when [MSV_Month] in (5) then [MSV_PaymentAmount] else 0 end) as MayMSV,
sum(case when [MS_Month] in (5) then [MS_Amount] else 0 end) as MaySML,
sum(case when [MSV_Month] in (6) then [MSV_PaymentAmount] else 0 end) as JunMSV,
sum(case when [MS_Month] in (6) then [MS_Amount] else 0 end) as JunSML,
sum(case when [MSV_Month] in (7) then [MSV_PaymentAmount] else 0 end) as JulMSV,
sum(case when [MS_Month] in (7) then [MS_Amount] else 0 end) as JulSML,
sum(case when [MSV_Month] in (8) then [MSV_PaymentAmount] else 0 end) as AugMSV,
sum(case when [MS_Month] in (8) then [MS_Amount] else 0 end) as AugSML,
sum(case when [MSV_Month] between 1 and 8 then [MSV_PaymentAmount] else 0 end) as TotalMSV,
sum(case when [MS_Month] between 1 and 8 then [MS_Amount] else 0 end) as TotalSML,
sum(case when [MSV_Month] between 1 and 8 then [MSV_PaymentAmount] else 0 end) -
sum(case when [MS_Month] between 1 and 8 then [MS_Amount] else 0 end) as Delta
from [dbo].[MSVTransaction] as msv
inner join [dbo].[MonthlySalary] as SmlTbl on SmlTbl.MS_EmployeeID =
msv.MSV_EntitledIdNumber
[MS_Semel] = '9'
and msv.[MSV_EntitledIdNumber] in (select distinct [MS_EmployeeID] from
[dbo].[MonthlySalary])
group by [MSV_EntitledIdNumber],[MS_Semel]
我得到的結果是不正確的。任何想法是什麼問題的代碼,我如何解決它,以獲得我想要的輸出?謝謝!
謝謝。那工作! – Jordan1200