如何根据variationID获取每个分类帐帐户的最新记录

时间:2018-05-23 15:55:08

标签: 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        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

我尝试使用以下代码来获取最大变体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 

请指导我如何获取这些数据的最新记录。

3 个答案:

答案 0 :(得分:0)

我的o / p仍然不清楚,但根据您的查询,它应该相关

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

答案 1 :(得分:0)

你走了:

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 |
+---------+--------------+--------+

请注意,Variation_id = 3没有Amount = 40,请更正您的问题。

答案 2 :(得分:0)

使用DENSE_RANK

select * 
from ( select * 
            , dense_rank() over (partition by account order BY variation_id desc) as rn
       from table 
     ) t
where t.rn = 1