获得最新的记录

时间:2013-11-23 09:24:06

标签: sql sql-server group-by

这是我的表

Select ClaimId
,InterestSubsidyClaimId
,BankId,BankName
,UpdatedPrincipalAmountofOutStanding
,[date] 

From InterestSubsidyReviseClaim 

Where IsActive = 1 and InterestSubsidyReviseClaim.InterestSubsidyClaimId=1 

给我的结果如gggggg

现在我只想记录3号和10号

我只有“InterestSubsidyClaimId”

结果记录应

trytt

那怎么办呢????

3 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER功能执行此操作。例如:

;WITH DataSource AS
(
    Select ROW_NUMBER() OVER (PARTITION BY BankName ORDER BY ClaimID DESC) AS [RowID]
          ,ClaimId
          ,InterestSubsidyClaimId
          ,BankId,BankName
          ,UpdatedPrincipalAmountofOutStanding
          ,[date] 
    From InterestSubsidyReviseClaim 
    Where IsActive = 1 and InterestSubsidyReviseClaim.InterestSubsidyClaimId=1 
)
SELECT ClaimId
      ,InterestSubsidyClaimId
      ,BankId,BankName
      ,UpdatedPrincipalAmountofOutStanding
      ,[date]
FROM DataSource
WHERE [RowID] = 1

答案 1 :(得分:1)

 Select ClaimId
 ,InterestSubsidyClaimId
 ,BankId,BankName
 ,UpdatedPrincipalAmountofOutStanding
 ,[date] 
From InterestSubsidyReviseClaim a
Where IsActive = 1 and InterestSubsidyReviseClaim.InterestSubsidyClaimId = 1
and exists (    
    select max(ClaimId)
    From InterestSubsidyReviseClaim b
    Where IsActive = 1 and InterestSubsidyReviseClaim.InterestSubsidyClaimId = 1
    group by BankId
    having max(claimid) = a.claimId
    )

答案 2 :(得分:1)

我自己解决了这个问题

Select ClaimId
,InterestSubsidyClaimId
,BankId,BankName
,UpdatedPrincipalAmountofOutStanding
,[date] 

From InterestSubsidyReviseClaim 

Where ClaimId=(

                   Select max(ClaimId)
                   From InterestSubsidyReviseClaim 
                   Where IsActive = 1 and InterestSubsidyReviseClaim.InterestSubsidyClaimId=1 
                   group by BankId

              )