76

我有一个查询返回我们系统中设置的汇率值。并非每个订单都有汇率 (currate.currentrate),因此它返回空值。

我可以让它返回 1 而不是 null 吗?

类似 if 语句的东西可能:

 if isnull(currate.currentrate) then 1 else currate.currentrate 

下面是我的查询。我非常感谢您的帮助!

 SELECT     orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  currrate.currentrate
 FROM         orderhed LEFT OUTER JOIN
                  currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate
4

6 回答 6

135

您可以使用CASE语句。

SELECT 
    CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...
于 2013-02-19T16:53:18.537 回答
51

您可以使用COALESCE

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    coalesce(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

甚至IsNull()

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    IsNull(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

这是一篇帮助在COALESCE和之间做出决定的文章IsNull

http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

于 2013-02-19T16:54:11.953 回答
16
SELECT 
    ISNULL(currate.currentrate, 1)  
FROM ...

比获胜答案更简洁,并且做同样的事情

https://msdn.microsoft.com/en-us/library/ms184325.aspx

于 2016-05-31T16:31:32.273 回答
4

a) 如果你想要 0 当值为 null

SELECT isnull(PartNum,0) AS PartNumber, PartID
FROM Part

b) 如果你想要 0 当 value 为 null 否则 1

SELECT 
  (CASE
    WHEN PartNum IS NULL THEN 0
    ELSE 1
  END) AS PartNumber,
  PartID
FROM Part
于 2017-05-16T11:18:50.023 回答
2
SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate  
于 2013-02-19T16:55:04.607 回答
0

尝试如下...

CASE 
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate
于 2013-02-19T16:56:03.530 回答