从where / like语句中选择存在多个记录的最新记录

时间:2012-02-16 13:09:29

标签: sql

请原谅我,如果标题(和我的SQL知识)看起来有点模糊,但我会尽可能清楚地解释。

我有一个表DVE_GroupMember,其中Person_StaffNumber是一个人的唯一标识符。在此表中有一列GroupMember_GroupName,其中包含可以分配给某个人的组名。

还有一列GroupMember_StartDate表示该人被分配到GroupMember_GroupName时。

一个人可以在一段时间内被分配到不同的组,所以如果我运行以下SQL,我会得到数据库中各种Person_StaffNumber值的多个结果(组名称包含'muster) “)

select * 
from DVE_GroupMember 
where GroupMember_GroupName like 'muster%'

我要做的是选择每个人被分配到的最新GroupMember_GroupName

我尝试了以下语法,但它生成了错误''附近的语法不正确')'

select * 
from DVE_GroupMember 
where GroupMember_GroupName like 'muster%' 
    and GroupMember_StartDate = (SELECT MAX(GroupMember_StartDate)

有人能帮我这个吗?

由于

4 个答案:

答案 0 :(得分:2)

SELECT
    * 
FROM
    DVE_GroupMember GM
WHERE
    GroupMember_GroupName LIKE 'muster%'
    AND GroupMember_StartDate = (
        SELECT
            MAX(GroupMember_StartDate)
        FROM
            DVE_GroupMember _GM
        WHERE
            _GM.GroupMember_GroupName LIKE 'muster%'
            AND _GM.Person_StaffNumber = GM.Person_StaffNumber)

答案 1 :(得分:0)

尝试以下方法:

select * 
from DVE_GroupMember 
where GroupMember_GroupName like 'muster%' 
    and GroupMember_StartDate = (SELECT MAX(GroupMember_StartDate) from DVE_GroupMember where GroupMember_GroupName like 'muster%')

答案 2 :(得分:0)

在SQL Server中,您可以使用cross apply,例如:

select   Staff.Person_StaffNumber
,        LastGroup.GroupMember_GroupName
from     (
         select  distinct Person_StaffNumber
         from    DVE_GroupMember 
         ) as Staff
cross apply
         (
         select  top 1 gm.GroupMember_GroupName
         from    DVE_GroupMember gm
         where   Staff.Person_StaffNumber = gm.Person_StaffNumber
         order by
                 GroupMember_StartDate desc
         ) as LastGroup

答案 3 :(得分:0)

这将为您提供最新组如Muster

的人
SELECT  gm.*
FROM    DVE_GroupMember gm
        INNER JOIN
        (   SELECT  Person_StaffNumber, MAX(GroupMember_StartDate) [MaxStartDate]
            FROM    DVE_GroupMember
            GROUP BY Person_StaffNumber
        ) MaxGm
            ON gm.Person_StaffNumber = MaxGm.Person_StaffNumber
            AND gm.MaxStartDate = maxGm.GroupMember_StartDate
WHERE   GroupMember_GroupName LIKE 'muster%'

这将为您提供每个工作人员的最新小组,其中小组就像Muster

SELECT  gm.*
FROM    DVE_GroupMember gm
        INNER JOIN
        (   SELECT  Person_StaffNumber, MAX(GroupMember_StartDate) [MaxStartDate]
            FROM    DVE_GroupMember
            WHERE   GroupMember_GroupName LIKE 'muster%'
            GROUP BY Person_StaffNumber
        ) MaxGm
            ON gm.Person_StaffNumber = MaxGm.Person_StaffNumber
            AND gm.MaxStartDate = maxGm.GroupMember_StartDate

我无法确切地确定你需要的是什么。