创建视图时如何解析空值

时间:2018-11-25 21:50:26

标签: mysql sql view

我需要创建一个这样的视图:

STUDENT JANUARY FEBRUARY MARCH ........ DECEMBER
miki     10.23   23.23    0               0
Goku     10        0       0               0
 Luffy    0       0        0               0

我有一张桌子studentMovement(id_studentmovement,id_student,month,year,cost,date,id_university,university_name)

代表该月和一年中学生的每笔花费。它包含某些学生在某所大学的某门课程中完成的实际费用。

Table Students(id_student,name)

Table University(id_university,university name);

我想为所有大学,所有学生和单身学生获得每月的费用(同样,如果该学生在某所大学中没有花任何钱,则为该费用:

此sql查询是这样的:

select year(sm.date) as year, s.id_student, s.name,
       sum(amount) as year_amount,
       sum(case when month(sm.date) = 1 then amount else 0 end) as january,
       sum(case when month(sm.date) = 2 then amount else 0 end) as february,
       . . .
       sum(case when month(sm.date) = 12 then amount else 0 end) as december,


       u.id_university as id_university,
       u.university_name as university_name
from ((schema.students s left join
     schema.studentMovement sm 
     on s.d_student = sm.id_student ) inner join schema.university u on u.id_university=sm.id_university) 

group by year(sm.date) as year, s.id_student, s.name,  u.id_university,
       u.university_name

该查询输入了错误的值,并且某些值为null。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

尝试仅在from子句中使用内部联接:

FROM schema.students s JOIN
     schema.studentMovement sm 
     ON s.d_student = sm.id_student JOIN
     schema.university u
     ON u.id_university = sm.id_university

答案 1 :(得分:0)

也许您在金额字段中发现了一些错误的值:尝试删除双引号

COALESCE(SUM(sm.amount), 0) AS amount,

答案 2 :(得分:0)

IconArrowUp值从您的do Null语句中出现。因为它返回来自Left Join的所有记录以及来自left table的匹配记录。如果不匹配,则结果是从右侧开始的right table

NULL

如果您不想看到select year(sm.date) as year, s.id_student, s.name, sum(amount) as year_amount, sum(case when month(sm.date) = 1 then amount else 0 end) as january, sum(case when month(sm.date) = 2 then amount else 0 end) as february, . . . sum(case when month(sm.date) = 12 then amount else 0 end) as december, u.id_university as id_university, u.university_name as university_name from ((schema.students s inner join schema.studentMovement sm on s.d_student = sm.id_student ) inner join schema.university u on u.id_university=sm.id_university) group by year(sm.date), s.id_student, s.name, u.id_university, u.university_name ,请将Null更改为Left Join,因为Inner Join选择两个表中具有匹配值的记录。