0

我有一张包含数百万笔交易的表格。我需要找到当前支付的最高金额。“当前”定义为发生最后一次取消交易之后。表格如下:

Id (guid)    ServiceId   CreatedDate               AmountPaid    InsurerId   IsCanceled
76E9A3...    19          2013-08-30 12:34:01.580   56.00         96          0
C3F325...    19          2013-08-30 12:34:02.069   14.95         110         0
96E9A3...    19          2013-08-30 12:32:01.540   109.00        95          1
C3BC25...    19          2013-08-30 12:32:02.007   15.95         108         1
85E9A3...    19          2013-08-30 12:30:01.701   101.00        95          0
A3F325...    19          2013-08-30 12:30:02.069   13.95         108         0

如您所见,对于同一个 serviceID,我有多个事务。我需要在这里检索的是 56 美元的交易,因为它是该 ServiceId在同一 ServiceID 最近取消的交易之后的最高交易。

如果我做:

 ORDER BY CreatedDate DESC, AmountPaid DESC

第一行将是 14.95 美元的交易......

如果我做:

ORDER BY AmountPaid DESC, CreatedDate DESC

第一行是 101 美元的交易

更多信息:

一旦服务交易被取消,任何交易都将失效。唯一有效的交易是在取消交易之后创建的交易。

4

2 回答 2

5
;WITH m AS
(
  SELECT ServiceID, m = MAX(CreatedDate) 
  FROM dbo.whatever 
  WHERE IsCanceled = 1 GROUP BY ServiceID
),
n AS
(
  SELECT w.*, 
    rn = ROW_NUMBER() OVER (PARTITION BY w.ServiceID ORDER BY w.AmountPaid DESC)
  FROM dbo.whatever AS w
  LEFT OUTER JOIN m ON w.ServiceID = m.ServiceID
  WHERE w.CreatedDate > COALESCE(m.m, '19000101')
)
SELECT * FROM n WHERE rn = 1;
于 2013-10-21T15:08:15.020 回答
1

您可以使用 aROW_NUMBER和 a CTE

WITH CTE AS
(
    SELECT t1.Id, t1.ServiceId, t1.CreatedDate, t1.AmountPaid,  t1.InsurerId, t1.IsCanceled,
        RN = ROW_NUMBER() OVER ( PARTITION BY t1.ServiceId
                                 ORDER BY t1.AmountPaid DESC, t1.CreatedDate DESC )
    FROM dbo.Transactions t1
    WHERE  t1.iscanceled = 0 
    AND (NOT EXISTS(SELECT 1 FROM dbo.transactions t2 
                    WHERE  t1.serviceid = t2.serviceid 
                    AND    t2.iscanceled = 1) 
     OR (t1.createddate > (
                   SELECT Max(createddate) 
                   FROM   dbo.transactions t2 
                   WHERE  t1.serviceid = t2.serviceid 
                   AND t2.iscanceled = 1)))
)
SELECT Id, ServiceId, CreatedDate, AmountPaid,  InsurerId, IsCanceled
FROM CTE
WHERE RN = 1

Demo

于 2013-10-21T14:51:11.137 回答