查询在存储过程中未按预期工作

Query not working as expected in stored procedure

下面是我的存储过程:

   ALTER PROCEDURE [dbo].[uspApprovalHistory]
        -- Add the parameters for the stored procedure here
                @empID int = null
    AS
    BEGIN
        declare @SRFTable table
        (SRFID nvarchar(50))
        declare @currSRFID nvarchar(50) = null
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
        -- Insert statements for procedure here
        insert into @SRFTable
        Select distinct MasterCode from CallForwarding 
        Where EmployeeNo = @empID or ApproverNo = @empID;
        Select *  From callforwarding 
        Where  Mastercode in (select SRFID from @SRFTable)
              and ApproverNo = @empID
              and ForwardDate in (Select max(ForwardDate) from CallForwarding
                              where Mastercode in (select SRFID from @SRFTable)
                              and ApproverNo = @empID)
    END

为什么它没有按预期工作?根据整个 table.

中的最大转发日期,它仅返回一行

我想要的是 SRFID = Mastercode 和 ForwardDate = Max(ForwardDate) 的所有行。有针对单个 SRFID 的多个记录,并且有多个 SRFID。我想要所有带有 SRFID 的行,其中转发日期是最近的。因此最终结果将是等于最近转发的 SRFID 的行。

尝试使用 GROUP BY:

Select *  From callforwarding 
Where  Mastercode in (select SRFID from @SRFTable)
    and ApproverNo = @empID
    and ForwardDate in 
               (Select max(ForwardDate) from CallForwarding
                where Mastercode in (select SRFID from @SRFTable)
                and ApproverNo = @empID
                group by Mastercode)

我假设这就是您真正想要的:

Select *  
From Callforwarding c1
Where  Mastercode in (select SRFID from @SRFTable)
and ApproverNo = @empID
and ForwardDate in 
(
    Select max(c2.ForwardDate) 
    from CallForwarding c2
    where c2.Mastercode = c1.MasterCode
    and ApproverNo = @empID
)

这样,最大日期只能从特定的 Mastercode 中选择,而不是从所有的 Mastercode 中选择。

其他替代方法是使用行号:

select * from (
  select
    Mastercode,
    ForwardDate,
    row_number() over (
      partition by MasterCode order by ForwardDate desc) as RN
  from
    Callforwarding
  where
    Mastercode in (select SRFID from @SRFTable)
    and ApproverNo = @empID
) TMP where RN = 1

SQLFiddle中的示例:Group by and Row Number