包括SQL查询输出中没有值的行

时间:2018-05-17 11:00:05

标签: sql sql-server tsql sql-server-2016

在我的SQL SERVER 2016数据库中运行以下查询:

SELECT
    u.idnumber,
    gi.idnumber AS code,
    gg.finalgrade AS grade
FROM
    grades AS gg 
INNER JOIN grade_items AS gi ON gg.itemid = gi.id 
INNER JOIN users AS u ON gg.userid = u.id
WHERE gi.idnumber IN ('436','434','313','002','135')
AND (u.idnumber = 'JohnBrown-xyz123);

给了我这个结果:

-------------------------
idnumber    code    grade
-------------------------
John12558   313     96
John12558   135     83

如何为所有5个gi.idnumber包含一行,包括没有成绩的行?

-------------------------
idnumber    code    grade
-------------------------
John12558   436
John12558   434
John12558   313     96
John12558   002
John12558   135     83

数据库表:

用户

id PK

grade_items

id PK

grade_grades

grade_grades.itemid FK(grade_items)

grade_grades.userid FK(用户)

3 个答案:

答案 0 :(得分:1)

您可以使用value构造:

select tt.idnumber, 
       t.idnumber AS code, 
       tt.grade 
from (values ('436'), ('434'), ('313'), ('002'), ('135')) t (idnumber) 
left join (select
                 u.idnumber,
                 gi.idnumber AS code,
                 gg.finalgrade AS grade
           from grades AS gg 
           inner join grade_items AS gi ON gg.itemid = gi.id 
           inner join users AS u ON gg.userid = u.id
           where u.idnumber = 'JohnBrown-xyz123') tt on left(tt.code, 3) = t.idnumber

如果 idnumber 具有数字类型,则您无需使用' '

答案 1 :(得分:0)

假设"没有价值"是NULL然后只需在您的WHERE添加一个额外条款:

WHERE (LEFT(gi.idnumber, 3) IN ('436','434','313','002','135')
   OR gi.idnumber IS NULL)

编辑:很明显,上面的内容不起作用,这意味着"没有价值"并不意味着NULL。相反,你可以尝试:

    WHERE (LEFT(gi.idnumber, 3) IN ('436','434','313','002','135','')

如果这不起作用,请提供消耗品样本数据,我们可以对其进行测试:Forum Etiquette: How to post data for a T-SQL Question

答案 2 :(得分:0)

您需要cross join才能看到所需内容:

select 
    u.idnumber,
    gi.idnumber code,
    ISNULL(gg.finalgrade, 0) grade
from  users u
    cross join grade_items gi
    left outer join grades gg on gg.itemid = gi.id  and gg.userid = u.id
where gi.idnumber in ('436','434','313','002','135')
    and u.idnumber = 'JohnBrown-xyz123'
finalgrade中的

空值不能替换为'N / A',因为它们是数字,而不是字符串,我将它们替换为零。