在取消任何交易后查找最高交易金额

时间:2013-10-21 14:46:42

标签: sql-server sql-server-2008

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

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 $交易

更多信息:

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

您可以使用ROW_NUMBERCTE

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