Sql 如何根据variationID获取每个分类科目的最新记录

Sql 如何根据variationID获取每个分类科目的最新记录,sql,sql-server,Sql,Sql Server,我在平衡表中有三列 account variation_id amount 101 1 20 101 1 10 101 2 10 101 2 50 110 4 13 110 3 20 110

我在平衡表中有三列

account   variation_id   amount     
  101        1            20
  101        1            10
  101        2            10
  101        2            50       
  110        4            13             
  110        3            20 
  110        4            40
  110        3            14   
  100        5            34    
  100        6            45
结果一定是这样,

account   variation_id   amount     
  101        2            10
  101        2            50       
  110        4            13             
  110        3            40  
  100        5            34    
  100        6            45
我试着用下面的代码来获取max variation id和数据,但没有成功。 我找到了所有与此相关的问题,但没有任何结果

select amount, account,VARIATION ID from balance a,
         (select max(VARIATION ID) as ID,account from balance 
          where account=account 
          group by account ) b
where a.account = b.account 

请指导我如何使用此数据获取最新记录。

我仍然不清楚您的o/p,但根据您的查询,它应该如下所示:

select b.*
from balance b
where variation_id = (select max(variation_id) 
                      from balance b1 
                      where b1.account = b.account
                     );
给你:

CREATE TABLE TBalance(
    Account INT,
    Variation_id INT,
    Amount INT
    );

INSERT INTO TBalance VALUES
(101, 1, 20),
(101, 1, 10),
(101, 2, 10),
(101, 2, 50),       
(110, 4, 13),             
(110, 3, 20), 
(110, 4, 40),
(110, 3, 14),   
(100, 5, 34),    
(100, 6, 45);

SELECT *
FROM TBalance TB1
WHERE TB1.Variation_id IN
    (
        SELECT MAX(Variation_id) AS Variation_id
        FROM TBalance TB2
        WHERE TB1.Amount >= TB2.Amount
        GROUP BY TB2.Account
    );
结果:

+---------+--------------+--------+
| Account | Variation_id | Amount |
+---------+--------------+--------+
|     101 |            2 |     10 |
|     101 |            2 |     50 |
|     110 |            4 |     13 |
|     110 |            4 |     40 |
|     100 |            5 |     34 |
|     100 |            6 |     45 |
+---------+--------------+--------+
请注意,id=3和金额=40之间没有差异,请更正您的问题。

使用


你应该有一个时间戳来知道最新的记录。以后用秩函数得到最新的两个记录;使用CTE作为选择金额、账户、变更ID、按账户超额分配的行数、按时间戳描述的订单作为等级选择*,从等级<3的CTE中请说明如何获得该结果表。不清楚变体1发生了什么?你是如何得到110340的?为什么返回100534?表中相同。我在想mybe这是一个视图;请在订单中添加BYHi Sami,我尝试了你的代码,它工作正常。非常感谢您。select*从select*开始,按帐户顺序按变量在分区上密集排列\u id desc as rn从表t开始,其中t.rn=1'和帐户类似于'10%'嗨,Sami,我按照您的代码进行了尝试,但执行查询需要很长时间。@rajini对我来说并不慢,它给你带来了你所需要的预期结果:谢谢你的回答。
select * 
from ( select * 
            , dense_rank() over (partition by account order BY variation_id desc) as rn
       from table 
     ) t
where t.rn = 1