SQLite:在 CASE 语句中使用 COALESCE

SQLite: Using COALESCE inside a CASE statement

我有两张表,一张是一个人的初始号码的记录,第二张是这个号码的变化记录。

在加入期间,我 coalesce(latest_of_series, initial) 为每个人获得一个单数。到目前为止还不错。

我也把这些号码分成一组,分别对这些组进行排序。我知道我能做到:

select
  coalesce(latest, initial) as final,
  case
    when coalesce(latest, inital) > 1 and coalesce(latest, inital) < 100 then 'group 1'
    -- other cases
  end as group
-- rest of the query

但这当然非常难读。

我试过了:

select
  coalesce(latest_of_series, initial_if_no_series) as value,
  case
    when value > 1  and value < 100   then 'group 1'
    -- rest of the cases
  end as group
-- rest of the query

但是 sqlite 抱怨 there's no column "value"

难道真的没有办法把之前合并的结果作为“变量”吗?

这不是 SQL 网站限制。这是一个 SQL 限制。

所有的列名都决定为一个。您不能在查询的第 2 行中定义一个列,然后在查询的第 3 行中引用它。所有列都源自您 select 的表格,每个列都是独立的,它们无法“看到”彼此。

但您可以使用嵌套查询。

select
  value,
  case 
    when value >= 1    and value < 100 then 'group 1'
    when value >= 100  and value < 200 then 'group 2'
                                       else 'group 3'
  end value_group
from
  (
    select
      coalesce(latest_of_series, initial_if_no_series) as value
    from
      my_table
    group by
      user_id
   ) v

这样,内层查询的列可以定为一列,外层查询的列也可以定为一列。根据具体情况,它可能会更快。