如何编写sql查询以获取每个成员的最后一个事务?

时间:2014-03-13 11:19:20

标签: mysql sql sql-server sql-server-2008

我的查询是这样的:

SELECT
    FOB_Id, MM_Id, CONVERT(varchar(25),FOB_Date,103), FOB_Balance, FOB_B_CR_DR  
FROM
    FO_Opening_Balance
WHERE
    MM_Id IN (1,597)
        AND month(FOB_Date)=1 
        AND YEAR(fob_date) = 2014
GROUP BY
    MM_Id, FOB_Id, FOB_Date, FOB_Balance, FOB_B_CR_DR  
ORDER BY
    FOB_Date desc, FOB_Id DESC

它将显示如下:

FOB_Id  | MM_Id | FOB_Date  |  Balance | cr/dr
-------------------------------------------------
625773  |  1    |31/01/2014 |   247.32 | Cr        
624391  | 597   |31/01/2014 |  1663.42 | Dr        
623999  |  1    |31/01/2014 |   447.32 | Cr        
622000  | 597   |31/01/2014 |  1551.42 | Dr        
621877  |  1    |31/01/2014 |   559.32 | Cr        
621473  |  1    |31/01/2014 |   865.32 | Cr        
620907  |  1    |24/01/2014 |   893.32 | Cr        
615844  | 597   |06/01/2014 |  1439.42 | Dr

但是我想只显示成员id的最后一个事务,如果我在select语句中给出前1,它将只显示一行,这里我给出了两个成员id 1和597,它应该只显示前两个上面的表行,如果给出很多成员id,它应该只显示那个成员事务,请帮忙。

2 个答案:

答案 0 :(得分:3)

我假设您正在使用SQL Server,基于查询语法。如果您想要最后一笔交易,可以使用row_number()

select FOB_Id,  MM_Id, dte, FOB_Balance, FOB_B_CR_DR
from (select FOB_Id,  MM_Id , convert(varchar(25), FOB_Date,103) as dte, FOB_Balance, FOB_B_CR_DR, FOB_Date,
             row_number() over (partition by mm_id order by fob_date desc) as seqnum
      from FO_Opening_Balance
      where MM_Id in (1,597) and
            month(FOB_Date) = 1 and YEAR(fob_date) = 2014
     ) t
where seqnum = 1
order by FOB_Date desc, FOB_Id desc;

答案 1 :(得分:0)

我会选择这样的东西:

SELECT FOB_Id, MM_Id, FOB_Date, FOB_Balance, FOB_B_CR_DR FROM FO_Opening_Balance
WHERE (MM_Id, FOB_Id) IN (SELECT MM_Id, MAX(FOB_Id) FROM FO_Opening_Balance GROUP BY MM_Id)
AND YEAR(FOB_Date) = 2014
AND MONTH(FOB_Date) = 1
AND MM_Id in (1, 597)