0

我很难想出一个查询。我对 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
)

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

4

3 回答 3

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;
于 2013-03-03T06:34:44.520 回答
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
于 2013-03-03T06:31:58.150 回答
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

这可能会帮助你

于 2013-03-03T06:32:12.373 回答