2013-10-21 92 views
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 $交易

更多信息:

服務交易取消後,任何交易都將失效。唯一有效的交易是在取消的交易之後創建的交易。

+3

那麼,爲什麼不應該它是101 $的交易呢?你如何定義近期足夠的? –

+0

56是高於109還是101? –

+0

我添加了一些額外的信息。 – Baral

回答

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; 
+0

我使用這段代碼,它工作得很好! – Baral

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

+0

這將返回14.95美元的交易(原因不明)不是理想的交易。 –

+0

@AaronBertrand:但OP只對'IsCanceled = 0'的行感興趣。根據期望的結果,我剛纔看到了OP提到的要求,而不是實際的數據。 –

+0

@MartinSmith:我更喜歡回答一個要求,而不是錯誤的樣本數據或不正確的結果。 –