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

时间:2015-05-30 07:10:20

标签: sql sql-server stored-procedures sql-server-2012

以下是我的存储过程:

 createCachedFile (MainActivity.this,"apk",adapter.getAppList ());

 ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile  (MainActivity.this, "apk");

为什么它没有按预期工作?它只返回一行,基于整个表中的最大转发日期。

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

2 个答案:

答案 0 :(得分:0)

尝试使用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)

答案 1 :(得分:0)

我认为这是你真正想要的:

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
)

这样,最大日期仅从该特定主代码中选择,而不是从所有主代码中选择。

其他替代方法如何使用行号:

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

SQL小提琴中的示例:Group byRow Number