我在哪里放if语句?

时间:2016-10-21 14:52:00

标签: sql-server if-statement group-by

我写这篇文章是为了创建过去30天的发票摘要。在检查发票时,我注意到我提取了很多空值,因为大多数客户都免税。我想提出一个IF声明(IF t.TAXABL_23 ='N'然后要使税收= 1 ......这里有点灰色) 在这个混乱的地方,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"

2 个答案:

答案 0 :(得分:1)

您可能正在寻找CASE表达式:

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

否则,如果您只想将NULL转换为某个值,则可以使用ISNULL表达式:

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

答案 1 :(得分:0)

使用 COALESCE 转换NULLS

 SELECT COALESCE(fieldWithNull, 'N');