如何在sql中使用dynamic if条件

时间:2015-10-12 06:13:37

标签: sql sql-server

我有一个powershell -Command "& {$xml = [xml](Get-Content '%InstConfXML%'); $xml.root.settings.installingUser.value = '%InstUsrXML%'; $xml.Save('%InstConfXML%')}" 查询,如下所示

SQL

它给出o / p如下

select TransactionMode as [Modes],
TransactionCode as [Codes], 
TransactionAmount as [Amount],SubTotal,Total 
from TransactionDetails where CurrentTime> CAST(GETDATE()as date)

我想根据 Modes Codes Amount SubTotal Total CARDS ICICI 12 13.18 13.18 CARDS ICICI 200 219.7 219.7 CARDS ICICI 500 549.25 549.25 BUY COD 7000 42.898 38.67 CARDS SBI 400 439.4 439.4 列计算佣金。我尝试了如下查询

TransactionMode

我期待o / p为

Declare @TransactionMode varchar(250);
set @TransactionMode='select TransactionMode from TransactionDetails'

IF @TransactionMode = 'CARDS'
    select transactioncode as [Type], count(TransactionCode) as [No of Trans], SUM(Total) as [Amount],
ABS(SUM(Subtotal-TransactionAmount)) as [Comission] from dbo.TransactionDetails  where CurrentTime> CAST(GETDATE()as date) and
     Status='Active' group by transactioncode

ELSE
   select transactioncode as [Type], count(TransactionCode) as [No of Trans], SUM(Total) as [Amount],
ABS(SUM(Subtotal-Total)) as [Comission] from dbo.TransactionDetails  
   where CurrentTime> CAST(GETDATE()as date)
    and Status='Active' group by transactioncode

相反,我正在

Type  No Of Trans   Amount    Comission
COD       1         38.67      4.228
ICICI     3         782.13     70.13
SBI       1         439.4      39.4

我哪里错了?

1 个答案:

答案 0 :(得分:1)

这是您的错误:您使用字符串'从TransactionDetails中选择TransactionMode'填充变量@TransactionMode。这永远不会等于'CARDS',所以你总是执行ELSE分支。

而是查看记录的交易模式:

select 
  transactioncode as [Type], 
  count(transactioncode) as [No of Trans], 
  sum(total) as [Amount],
  abs(sum(case when transactionmode = 'cards' then subtotal - transactionamount 
                                              else subtotal - total end)) as [Comission] 
from dbo.transactiondetails  
where currenttime > cast(getdate() as date) 
and status = 'active' 
group by transactioncode;

(顺便说一下,abs(sum(a-b))公式似乎很奇怪。结果是正面还是负面都不重要吗?)