在多个where条件中选择具有最大值的行

时间:2019-01-26 21:14:26

标签: sql-server tsql select

我根据此页面编辑了以下查询:

Selecting a Record With MAX Value

选择查询:

select 
    Users.Id, Users.[Name], Users.Family, Users.BirthDate,
    Users.Mobile, Users.[Description], Users.Email,
    Users.UserName, Users.fatherName,
    Users.archiveNumber, Users.[Address], Users.IsMarried,
    Users.Mazhab, 
    Cities.CityName, Religions.PersianName, Users.Date_insert, 
    Users.ImageName,
    MaghtaeTahsilis.[Name] as MaghtaeTahsilisName,
    FieldStudies.[Name] as FieldStudiesName,
    Eductionals.Institute, Eductionals.Moaddal, 
    Eductionals.FromYear, Eductionals.ToYear
from 
    Users 
left outer join 
    Eductionals on Users.id = Eductionals.UserID
left outer join 
    MaghtaeTahsilis on Eductionals.MaghtaeID = MaghtaeTahsilis.ID
left outer join 
    Cities on Users.City_Id = Cities.Id
left outer join 
    Religions on Users.Relegion_ID = Religions.ID
left outer join 
    FieldStudies on Eductionals.FieldStudy_ID = FieldStudies.ID
where 
    Users.UserName = @code_melli 
    and Eductionals.MaghtaeID = (select MAX(MaghtaeID) from Eductionals 
                                 where Eductionals.UserID = Users.Id)

此命令可以正确选择MAX值,但是如果以下语句具有NULL值,则不会返回任何行。我想显示NULL的值,如果它是NULL

2 个答案:

答案 0 :(得分:1)

您的left outer joininner join条件变成where。您的查询应类似于:

select u.Id, u.[Name], u.Family, u.BirthDate, u.Mobile, u.[Description], u.Email, u.UserName, u.fatherName,
       u.archiveNumber, u.[Address], u.IsMarried, u.Mazhab, c.CityName, r.PersianName, u.Date_insert, u.ImageName,
       mt.[Name] As MaghtaeTahsilisName, fs.[Name] As FieldStudiesName, e.Institute, e.Moaddal, e.FromYear, e.ToYear
from Users u left outer join
     Eductionals e
     on u.id = e.UserID and
        e.MaghtaeID = (select MAX(e2.MaghtaeID)
                       from Eductionals e2
                       where e2.UserID = u.Id
                      ) left outer join
     MaghtaeTahsilis mt
     on e.MaghtaeID = mt.ID left outer join
     Cities c
     on u.City_Id = c.Id left outer join
     Religions r
     on u.Relegion_ID = r.ID left outer join
     FieldStudies fs
     on e.FieldStudy_ID = fs.ID
where u.UserName = @code_melli ;

第一个表中的条件-在left join链中应该位于where子句中。在on子句中的后续表上。

您会注意到,我还添加了表别名,因此查询更易于编写和阅读。

您还可以使用窗口功能:

from Users u left outer join
     (select e2.*,
             row_number() over (partition by e2.userId order by e2.MaghtaeID desc) as seqnum
      from Eductionals e2
     ) e
     on u.id = e.UserID and
        e.seqnum = 1 left outer join
     . . .

答案 1 :(得分:0)

第二个查询返回NULL时返回零记录的原因是,第二个查询返回NULL时,您的SQL语法变成这样

And Eductionals.MaghtaeID=NULL

可能Dbtable Educationals保留字段MaghtaeID的NULL值。 因此,SQL无法使用上述语法,因此返回零记录。 用于检查NULL值的正确语法为

And Eductionals.MaghtaeID is NULL

因此,请按如下所示修改查询条件,以返回所需结果。

where Users.UserName = @code_melli AND isnull(Eductionals.MaghtaeID,0) = isnull((select MAX(MaghtaeID) from Eductionals where Eductionals.UserID = Users.Id),0)