SQL查询所需的最新事务总和

时间:2013-03-03 06:27:22

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

我很难提出查询。我对SQL很新,所以解决方案看起来很明显对老手来说很明显,但我老老实实地试过了,再也想不到了。我有一个名为Transactions的表,它有相关的列:ID(int),CustomerID(int),Amount(int)和TransactionDate(date)。我想要所有客户最新交易的总和。可以手动输入/更改TransactionDate,因此如果在该最新日期有多个事务,则ID将仅用作辅助排序参数。

在变得沮丧之前我有什么:

SUM (
    SELECT  TOP 1 Amount
    FROM    Transactions
    GROUP   BY CustomerID
    ORDER   BY TransactionDate DESC, ID DESC
)

我知道为什么它是错的,它可能甚至不能接近我需要的东西,但我不知道如何解决它。

3 个答案:

答案 0 :(得分:3)

试试这个:

WITH CTE
AS
(
  SELECT Amount,
    ROW_NUMBER() OVER(PARTITION BY CustomerID
                      ORDER BY TransactionDate DESC, ID DESC) AS RN
  FROM Transactions
)
SELECT SUM(Amount)
FROM CTE
WHERE RN = 1;

答案 1 :(得分:0)

试试这个

SELECT id, CustomerID, Amount
FROM (
    SELECT 
        id, CustomerID, Amount
        ,rank() over(Partition BY CustomerID ORDER BY TransactionDate,id DESC ) AS Rank 
    from Transactions
) AS a
WHERE a.Rank<=1

答案 2 :(得分:0)

DECLARE @FromDate DATETIME, @ToDate DATETIME
SELECT @FromDate = '1/1/2009', @ToDate = '1/1/2010'

SELECT SUM(Amount)
FROM    Transactions
WHERE TransactionDate BETWEEN @FromDate AND @ToDate
GROUP   BY CustomerID
ORDER   BY TransactionDate DESC, ID DESC

这可能对您有所帮助