2016-10-21 91 views
0

我寫了這個來創建過去30天的發票摘要。在檢查發票時,我注意到我拉了很多空值,因爲大多數客戶都是免稅的。我想提出一個IF聲明(如果t.TAXABL_23 ='N'然後是使稅收= 1的東西...它在這裏變得有點灰) 在這個混亂的地方if語句會去,或者更好的是使用一個IF語句是這樣做的邏輯方法。 謝謝。我在哪裏放置if語句?

Select c.ordnum_31 as "Sales Order Number", 
    c.invce_31 as "Invoice Number",  
    c.custpo_31 as "Job Name", 
    c.ordid_31 as "Other Job Name", 
    c.invdte_31 as "Invoice Date", 
    cast (sum((1-(m.DSCRTE_23/100)) * (o.price_32 * o.shpqty_32)) as decimal (8,2)) as "Net Amount", 
    cast (c.frtamt_31 as decimal(8,2)) as Freight, 
    cast(((t.TAXRTE_25 * .01) * c.TAXTOT_31) as decimal (8,2)) as Tax, 
    cast (c.MSCAMT_31 as decimal(8,2)) as MISC, 
    cast(round (sum((1-(m.DSCRTE_23/100)) * (o.price_32 * o.shpqty_32)) + c.frtamt_31 + c.MSCAMT_31 + ((t.TAXRTE_25 * .01) * c.TAXTOT_31),1) as decimal(8,2)) as "Invoice Total" 

from Invoice_Master c 
    left join Invoice_Detail o on c.ORDNUM_31 = o.ORDNUM_32 
    left join Customer_Master m on c.CUSTID_31 = m.CUSTID_23 
    left join Tax_master t on m.TXCDE1_23 = t.TAXCDE_25 

where c.invdte_31 >= DATEADD(day,-30, getdate()) 

group by 
    c.ORDNUM_31, 
    c.CUSTID_31, 
    c.INVCE_31, 
    c.CUSTPO_31, 
    c.ORDID_31, 
    c.INVDTE_31, 
    c.frtamt_31, 
    c.taxtot_31, 
    m.dscrte_23, 
    c.MSCAMT_31, 
    t.taxrte_25 

order by "Invoice Number" 
+0

它們實際上是否爲NULL或是否是N''? – BJones

+0

你可以包含一些樣本數據和預期的輸出嗎? –

+0

@bjones,如果納稅標誌是N,則它們爲NULL。 – Onyxtacular

回答

1

您可能正在尋找一個CASE表達式:

... 
... as Freight, 
CASE WHEN t.TAXABL_23 = 'N' 
    THEN 0     -- exempt from taxes 
    ELSE ...calculate tax... 
END as Tax, 
... as MISC, 
... 

否則,如果你只是想空值轉換爲一定的價值,你可以使用ISNULL表達:

... 
ISNULL(...calculate tax..., 0) AS tax -- yields 0 when the result of the expression is NULL 
... 
+0

我試過你的第一個例子....這就是我想出的: – Onyxtacular

+0

CASE WHEN t.TAXABL_23 ='N' \t then cast(round(sum((1-(m.DSCRTE_23/100))*( (((t.TAXRTE_25 * .01)*)作爲「發票總數」 ELSE \t \t cast((t.TAXRTE_25 * .01)*)+ c.frtamt_31 + c.MSCAMT_31,1) (sum((1-(m.DSCRTE_23/100))*(o.price_32 * o.shpqty_32))+ c.frtamt_31(c.TAXTOT_31)作爲十進制(8,2))作爲稅, \t \t cast + c.MSCAMT_31 +((* t.TAXRTE_25 0.01)* c.TAXTOT_31),1)爲十進制(8,2))爲 「發票總額」, \t \t端 從Invoice_Masterç 但語法關閉...你能擴展你的答案嗎?謝謝 – Onyxtacular

+0

以及評論看起來像廢話,我找不到如何刪除它...對不起 – Onyxtacular

0

使用COALESCE轉換成NULLS

SELECT COALESCE(fieldWithNull, 'N'); 
+1

爲什麼只有一個值時使用'COALESCE'? – Jens

+0

OP說越來越多的null,而不是'NULL'想要''N''。 –

+0

是的,但是在這種特殊情況下,爲什麼你更喜歡'COALESCE'而不是'ISNULL'? 「ISNULL」對我來說似乎是合乎邏輯的選擇。 – Jens