SQL获取每个帐户的第一个日期和金额

时间:2017-05-19 19:16:15

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

我想在交易表中找回每个帐户的第一笔交易的日期和金额。表(GiftHeader)如下所示:

EntityID           Date                        Amount
1                 1/1/2027  00:00:00:00        1.00
1                 2/1/2027  00:00:00:00        2.00
2                 2/1/2027  00:00:00:00        4.00
2                 3/1/2027  00:00:00:00        2.00

在这种情况下,我希望如下:

EntityID          BatchDate                    Amount
1                 1/1/2027  00:00:00:00        1.00
2                 2/1/2027  00:00:00:00        4.00

这是我正在使用的SQL无效。

select DISTINCT entityid, min(BatchDate) as FirstGiftDate 
from GiftHeader
group by EntityId,BatchDate
order by EntityId

任何帮助都将不胜感激。

此致

Joshua Goodwin

2 个答案:

答案 0 :(得分:1)

您可以使用带有以下关系的前1

Select top 1 with ties * from GiftHeader
    order by row_number() over (partition by entityid order by [BatchDate])

其他传统方法是

Select * from (
   Select *, RowN = row_number() over (partition by entityid order by BatchDate) from GiftHeader  ) a
Where a.RowN = 1

输出:

+----------+-------------------------+--------+
| EntityId |        BatchDate        | Amount |
+----------+-------------------------+--------+
|        1 | 2027-01-01 00:00:00.000 |      1 |
|        2 | 2027-02-01 00:00:00.000 |      4 |
+----------+-------------------------+--------+

答案 1 :(得分:0)

您可以使用ROW_NUMBER,如下所示

SELECT EntityID, 
       Date, 
       Amount 
FROM   (SELECT ROW_NUMBER() 
                 OVER ( 
                   PARTITION BY EntityID 
                   ORDER BY Date) AS RN, 
               * 
        FROM   GiftHeader) a 
WHERE  a.RN = 1