1

I have a table that includes the following columns:

UserName (nvarchar), TransactionDateTime (datetime), Balance (money).

Each time a user makes a transaction, this is recorded as a row in the table.

The majority of users have multiple transactions stored in the database.

I want to write an SQL query that takes the most recent TransactionDateTime for each UserName and then creates a total of all these balances.

I do not want to include the balances of any user transactions apart from the most recent for each user.

I hope that I have explained this clearly. Any help is gratefully appreciated.

Using Microsoft SQL Server 2008 and SQL management studio 2008.

Thanks, Nelson

4

2 回答 2

0
  select UserName, max(TransactionDateTime), sum(Balance)
  from tablename group by Username Having TransactionDateTime=max(TransactionDateTime)
于 2013-08-02T15:47:13.453 回答
0

我发现了如何做到这一点:

SELECT SUM(Balance) AS Total_Balance FROM tablename a WHERE TransactionDateTime = ( SELECT MAX(TransactionDateTime) FROM tablename b WHERE a.UserName = b.UserName)

于 2013-08-05T12:18:34.053 回答