【问题标题】:SQLITE - If a column is null then the value in another column is 0SQLITE - 如果一列为空,则另一列中的值为 0
【发布时间】:2020-09-03 17:36:48
【问题描述】:

我在一个表中有两列。表名是用inner join和group by构造的,我们称这个表为Joined。它有两列Present 和Score。如果Present 为null,那么我想将0 分配给Score 值。

+------------+--------+-------------+------------+--------+
| Student_Id | Course | ExamDate    |  Present   | Score  |
+------------+--------+-------------+------------+--------+
|       1    | Math   | 04/05/2020  | Yes        | 45     |
|       2    | Math   | 04/05/2020  | NULL       | 90     |
|       2    | Math   | 04/05/2020  | NULL       | 50     |                     
+------------+--------+-------------+------------+--------+

我现在拥有的是

SELECT DISTINCT StudentID ,Course, ExamDate, Present, Score
CASE Present ISNULL
Score = 0
END
    FROM Joined

我需要不同的,因为内部连接可以给我一些重复。我需要的是

+------------+--------+-------------+------------+--------+
| Student_Id | Course | ExamDate    |  Present   | Score  |
+------------+--------+-------------+------------+--------+
|       1    | Math   | 04/05/2020  | Yes        | 45     |
|       2    | Math   | 04/05/2020  | NULL       | 0     |
+------------+--------+-------------+------------+--------+

这对我来说感觉非常非常错误,但我无法通过一个查询弄清楚如何做到这一点。我该怎么做?

【问题讨论】:

  • 请提供样本数据和期望的结果。
  • 谢谢,我加了例子

标签: sql sqlite case sql-null


【解决方案1】:

如果 Present 为空,我想将 0 分配给 Score 值。

case 表达式如下:

select 
    present,
    case when present is null 
        then 0 
        else score 
    end as score
from ...

当present 不是 null 时,你不知道该怎么做 - 所以这会返回原始的 score。

尚不清楚您为什么需要distinct。如果您要询问有关似乎会产生(部分)重复的原始查询的问题,on 可能会帮助解决它。

【讨论】:

    【解决方案2】:

    你可以试试下面的-

    SELECT DISTINCT StudentID ,Course, ExamDate, Present, Score,
    CASE when Present IS NULL
    then 0 else score END as scoreval
    FROM Joined
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多