为查询中的一列写 CASE 条件

Write CASE condition for one column in the Query

我有一个查询,我想在其中应用 CASE 条件。这是我的查询:

Select 
    a.mkey, a.party_name, a.doc_no Inward_No, 
    c.type_desc Doc_Type, a.ref_no, 
    convert(varchar(25),a.ref_date,103) Ref_date,
    a.Inward_amt, b.first_name + ' ' + b.last_name ToUser --- here
from 
    inward_doc_tracking_hdr a
inner join 
    user_mst b on a.To_User = b.mkey
inner join 
    type_mst_a c on a.doc_type = c.master_mkey  
                 and a.mkey =227423

我想要的是:如果我得到 ToUser 作为 NULL 那么我想用 Last_To_User 代替它。

如何在 SQL 服务器中执行此操作?

不需要区分大小写,您可以使用将 return 第一个非空值的合并函数:

b.first_name + ' ' + b.last_name + coalesce(Touser,Last_To_User)

而不是 b.first_name + ' ' + b.last_name 使用以下内容:

CASE
 WHEN b.first_name IS NULL THEN b.first_name + ' ' + b.last_name
 ELSE Last_To_User
END

现在问题很清楚了,我告诉你这个,你用inner join join table user_mst 条件是To_User 所以你已经过滤了行有 To_User 的是 null,你知道,Null 不能连接到任何东西,所以尽量让它离开 join

Select a.mkey, a.party_name, a.doc_no Inward_No, c.type_desc Doc_Type, a.ref_no, 
    convert(varchar(25),a.ref_date,103) Ref_date,
            a.Inward_amt, 
            case when To_User is null then Last_To_User
            else b.first_name + ' ' + b.last_name end as ToUser --- here
        from inward_doc_tracking_hdr a
    left join user_mst b
on a.To_User = b.mkey
        inner join type_mst_a c
    on a.doc_type = c.master_mkey   
    and a.mkey =227423    

试试这个 - 只需在名字和姓氏的前后使用 ISNULL

Select 
    a.mkey, a.party_name, a.doc_no Inward_No, 
    c.type_desc Doc_Type, a.ref_no, 
    convert(varchar(25),a.ref_date,103) Ref_date,
    a.Inward_amt, 
    -- if the first_name+last_name is NULL, then take Last_To_User instead
    ISNULL(b.first_name + ' ' + b.last_name, Last_To_User) ToUser 
from 
    inward_doc_tracking_hdr a
inner join 
    user_mst b on a.To_User = b.mkey
inner join 
    type_mst_a c on a.doc_type = c.master_mkey  
                 and a.mkey =227423

我认为您的 post 让大多数人感到困惑,也可能让我感到困惑。阅读评论后,如果它 IS NOT NULL,你似乎想要 To_User(该列,而不是你的 b.first_name + ' ' + b.last_name 的别名列),但如果它 IS NULL 那么你想要Last_to_User。因此你应该像这样使用 COALESCE

COALESCE(To_User,Last_To_User,'')

这将为您提供列表中的第一个 NOT NULL 值。所以,如果 To_User IS NOT NULL 它将被返回。如果它 IS NULL 则将返回 Last_To_User,除非它也是 NULL,在这种情况下将返回一个空白。

我不确定我是否比其他人更不困惑,我不是专家,这可能看起来很简陋,但我最简单的回答是;

WITH QUERY1 AS (

Select 
a.mkey, 
a.party_name, 
a.doc_no AS Inward_No, 
c.type_desc 
Doc_Type, 
a.ref_no, 
convert(varchar(25),a.ref_date,103) AS Ref_date,
a.Inward_amt, 
b.first_name + ' ' + b.last_name AS ToUser --- here
from 
inward_doc_tracking_hdr a
inner join 
user_mst b on a.To_User = b.mkey
inner join 
type_mst_a c on a.doc_type = c.master_mkey  
             and a.mkey =227423
             )
SELECT *,
   CASE WHEN ToUser IS NULL
   THEN Last_To_User
   ELSE ToUser
FROM QUERY1