如何通过人 - SQL Server获取最新和不同列的最新记录?

时间:2017-11-14 23:06:31

标签: sql-server

我需要在交易表中获得最早的上一次余额每个人的最新实际余额

例如,我得到了这个:

+-----------------+---------------+-----------------+---------------+
| dateTransaction | idPerson      | previousBalance | actualBalance |
+-----------------+---------------+-----------------+---------------+
| 01-11-2017      |      1        |       0         |    1000       |
| 02-11-2017      |      2        |       500       |    2000       |
| 03-11-2017      |      1        |       1000      |    1500       |
| 04-11-2017      |      2        |       2000      |    2500       |
+-----------------+---------------+-----------------+---------------+

所以我需要得到这样的东西:

+---------------+-----------------+---------------+
| idPerson      | previousBalance | actualBalance |
+---------------+-----------------+---------------+
|      1        |       0         |    1500       |
|      2        |       500       |    2500       |
+---------------+-----------------+---------------+

这是创建表格的脚本:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Transaction]
(
    [numberTransaction] [int] NOT NULL,
    [dateTransaction] [datetime] NOT NULL,
    [idPerson] [decimal](20, 0) NOT NULL,
    [transactionAmount] [decimal](18, 3) NOT NULL,
    [previousBalance] [decimal](18, 3) NOT NULL,
    [actualBalance] [decimal](18, 3) NOT NULL,

    CONSTRAINT [PK_Transaction] 
        PRIMARY KEY CLUSTERED ([numberTransaction] ASC)
) ON [PRIMARY]
GO

提前致谢...

1 个答案:

答案 0 :(得分:1)

使用row_number() over(),如下所示:

SELECT *
FROM (
    SELECT t.*
    , row_number() over(partition by idPerson order by dateTransaction ASC) as is_oldest
    , row_number() over(partition by idPerson order by dateTransaction DESC) as is_newest
    FROM Transaction t
     ) d
WHERE ( is_oldest = 1 OR is_newest = 1 )
ORDER BY idPerson, dateTransaction ASC

over clause中,partition by表示row_number()分配的数字将 PER idPerson 。然后order by在最早的日期(当分类为asending时)设置1或在最新的日期设置1(当按降序排序时)。