【问题标题】:T-SQL Can't get CASE statement to choose just one alternativeT-SQL 无法让 CASE 语句只选择一种替代方法
【发布时间】:2015-12-30 23:03:33
【问题描述】:

在我们的系统中,每个客户都有一个称呼 (0),有些客户还有另一个额外的称呼 (22)。我需要做的是让那些没有 22 的人默认为 0 。我正在尝试使用 case 语句来完成此操作:

select distinct a.customer_no,
case when b.sal_code = '22' then '22' 
    when b.sal_code <> '22' then '0'
    else '0'
end as salutation_no
from t_customer a
    join t_sal b
on a.customer_no = b.customer_no    
where a.customer_no in (1734379, 120706)

但是,我没有为有 22 分的客户获得 22 分,而没有为那些没有获得 0 分的客户获得 0 分,而是为所有客户获得 0 分,同时为那些也有 22 分的客户获得额外的 22 分:

customer_no salutation_no
120706       0
120706       22
1734379      0

【问题讨论】:

  • 我认为 T-SQL 的不等于运算符是 "!=" 参见 post
  • incorrect 在 TSQL 中很好,但你也可以使用 != (我更喜欢 )
  • DISTINCT 不仅仅适用于一列,它适用于所有选定的列。如果有两个 a 值具有不同的 b 值,SELECT DISTINCT a, b 给出两行。请参阅@Szymon 的解决方案,它应该适合您。

标签: sql tsql case


【解决方案1】:

您会获得双重记录,因为某些客户有 2 个称呼,而加入的结果是那些双重记录。

您可以使用此查询获取一条记录。它使用max 函数,因为您希望 22 覆盖 0。

select a.customer_no,
    max(sal_code) as salutation_no
from t_customer a
    join t_sal b
on a.customer_no = b.customer_no    
where a.customer_no in (1734379, 120706)
group by a.customer_no

【讨论】:

    【解决方案2】:

    只有在输入 '22' 时才加入问候语,所有其他人现在将有 null 用于 sal_code。使用coalesce 默认null'0'

    select C.customer_no
        , coalesce(S.sal_code, '0') as salutation_no
    from t_customer C
    left join t_sal S
        on S.customer_no = C.customer_no
        and S.sal_code = '22'
    where S.customer_no in (1734379, 120706)
    
    1. 不清楚数据模型,是否需要distinct
    2. 这将包括t_customer 中没有行的t_sal 行,这些行将在您的查询中被过滤掉。在不知道数据的情况下,我不能 100% 确定这是一个合适的解决方案。

    【讨论】:

      【解决方案3】:

      另一种避免重复的方法是使用union all

      select s.customer_no, '22' as sal_code
      from t_sal s
      where s.sal_code = '22'
      union all
      select c.customer_no, '0'
      from t_customer c
      where not exists (select 1 from t_sal s where s.customer_no = c.customer_no and s.sal_code = '22');
      

      这应该比使用group byselect distinct 的任何查询都要快。

      【讨论】:

        猜你喜欢
        • 2015-02-11
        • 2014-12-17
        • 1970-01-01
        • 2017-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多