使用来自2个位置的值填充列

时间:2015-10-29 03:21:46

标签: sql-server

在下面的SQL中,如果select无法在查找表中找到值,则Bank列将返回一个emty字符串('')。我想在字段b.BankName

中显示值,而不是空字符串
SELECT 
' ' AS DUMMY, 
c.CustomerNumber AS DirectDebitRef,
(SELECT replace(bankname, 'Other (please specify)', '')
 FROM Banks
 WHERE bankid = b.bankid) AS Bank, 
b.SortCode AS SortCode
FROM 
dbo.Customers AS c 
INNER JOIN dbo.CustomerBanks AS b ON c.CustomerBankId = b.CustomerBankId
INNER JOIN dbo.View_CustomerBillingsToday AS v ON c.CustomerId = v.CustomerId 
INNER JOIN dbo.CustomerAddressBillings AS s ON c.CustomerAddressBillingId = s.CustomerAddressBillingId

我添加b.BankName的那一刻,我在所有具有有效查找的行中获得NULL输出。如果我用'' x'替换b.BankName我得到了所有行的值。所以我知道替换工作,但是当我尝试引用有效的fieldname时,它会使所有其他行为空

replace( (SELECT        bankname
                               FROM            Banks
                               WHERE        bankid = b.bankid), 'Other (please specify)', b.BankName) AS Bank

1 个答案:

答案 0 :(得分:0)

案例陈述有效,使用它而非替换做了诀窍: - )

 case WHEN (SELECT bankname
                               FROM            Banks
                               WHERE        bankid = b.bankid) = 'Other (Please Specify)' THEN b.BankName
                               ELSE (SELECT bankname
                               FROM            Banks
                               WHERE        bankid = b.bankid)
                               END AS Bank