SQLITE -如果一列为空,则另一列中的值为0

wqnecbli  于 2023-03-03  发布在  SQLite
关注(0)|答案(2)|浏览(168)

我在一个表中有两列。表名是用内部连接和group by构造的,我们把这个表命名为Joined。它有两列PresentScore。如果Present为空,那么我想把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

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

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

我觉得这非常非常不对,但是我一直不知道如何用一个查询来完成它,我该怎么做呢?

voase2hg

voase2hg1#

如果Present为空,则我希望将0分配给Score值。
case表达式如下所示:

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

presentnotnull时,您不需要告诉我们该怎么做--因此这将返回原始的score
现在还不清楚为什么需要distinct,如果您要问一个关于原始查询的问题,它似乎产生了(部分)重复,也许可以帮助修复它。

e5nszbig

e5nszbig2#

你可以试试下面的-

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

相关问题