将保留Null值的SQL脚本

时间:2017-09-07 03:14:35

标签: sql

我有一个SQL脚本,它返回第4列中的数据。返回的数据是Null值和前端帐户的SQL代码。我需要转换值,以便前端帐户显示,但也保留所有空值。当我运行我的SQL脚本并替换前端值时,我会丢失空值,总体结果总数会减少。

转换的示例脚本前端值:

Select c.Customer
, c.name
, l.City
, a.account
, case '#sortby#'
    when 'Customer' then c.customer
    else c.name end
from customer c, location l, Account a
where c.hmycustomer = l.hmy
and c.code = a.hmy

但是如果我像这样运行脚本,我得到的所有结果都包括Null,但值是hmy而不是前端代码。

Select c.Customer
, c.name
, l.City
, c.code
, case '#sortby#'
    when 'Customer' then c.customer
    else c.name end
from customer c, location l
where c.hmycustomer = l.hmy
enter code here

Customer |Name |City |Code 
---------|-----|-----|-----
   1     |John |Santa|Null
   2     |Mary |Santa|268
   3     |Josh |Santa|273
   4     |Bert |Santa|Null

code 268 should =1234
code 273 should =4563

1 个答案:

答案 0 :(得分:0)

左连接将返回客户表中的所有记录,请检查它:

SELECT
    c.Customer, c.name, l.City, a.account, c.code, a.hmy,
    CASE '#sortby#'
        WHEN 'Customer' THEN c.customer
        ELSE c.name 
    END
FROM
    ((customer c
LEFT JOIN 
    location l ON c.hmycustomer = l.hmy)
LEFT JOIN 
    Account a ON c.code = a.hmy);