2010-03-04 50 views
2

我有一個名爲'Table1'的表格,我需要根據這個條件檢索'金額'。如果'貨幣'是某個'美元',我想要金額顯示在小數點後1位。如果貨幣不是'美元',金額應該在2個小數位。我已經使用了case-else條件。但它沒有檢查條件,但只顯示更大的小數點我的查詢如下。Case-Else for SQL中的十進制值

Select InvNo, 
Case Currency when 'Dollar' then 
    Convert(decimal(18,1),Amount) 
Else 
    Convert(decimal(18,2),Amount) 
End 
'Amount' 
From Table1 where ID=1 

我的輸出如下:

InvNo金額

236 5200.26


如果我逆轉的條件下,我得到的結果相同。

Select InvNo, 
Case Currency when 'Dollar' then 
    Convert(decimal(18,2),Amount) 
Else 
    Convert(decimal(18,1),Amount) 
End 
'Amount' 
From Table1 where ID=1 

我的輸出如下:

InvNo金額

236 5200.26


也就是說,它不檢查condition.But它僅考慮最大的小數位。請幫忙。

回答

2

嘗試使用ROUND代替

DECLARE @Table1 TABLE(
     ID INT, 
     Currency VARCHAR(10), 
     Amount FLOAT 
) 

INSERT INTO @Table1 SELECT 1, 'Dollar', 5200.26 
INSERT INTO @Table1 SELECT 1, 'Pound', 5200.26 

Select 
     Case Currency when 'Dollar' then 
      CAST(Amount AS decimal(18,1)) 
     Else 
      CAST(Amount AS decimal(18,2)) 
     End 'Amount', 
     Case Currency when 'Dollar' then 
      ROUND(Amount,1) 
     Else 
      ROUND(Amount,2) 
     End 'Amount' 
From @Table1 
where ID=1 

輸出

Amount         Amount 
--------------------------------------- ---------------------- 
5200.30         5200.3 
5200.26         5200.26 
+0

1很好的例子代碼 – 2010-03-04 12:19:19