Complex Sql Select语句包含最新数据

时间:2015-03-11 23:57:05

标签: sql sql-server select subquery

我有一个可以在给定的一天或一周内运行多次的流程。我需要弄清楚已取消订单的折扣金额。

有以下两个表

交易

TransactionId,   Date,       Type,    OriginalId
1                2015-1-1    Order    
2                2015-1-1    Order 
3                2015-1-1    Order  
4                2015-1-2    Return   2
5                2015-1-2    Order

DiscountTransactions - 保存在给定运行时间获得折扣的所有交易的记录。

RunId,  TransactionId,   DiscountPercent, Date 
1       1                20%              2015-1-1
1       2                20%              2015-1-1
1       3                20%              2015-1-1
(running program second time, however different discount was applied)
2       1                45%              2015-1-1
2       2                45%              2015-1-1
2       3                45%              2015-1-1
(running program third time, for 2015-1-2)
3       4                45%              2015-1-2
3       5                45%              2015-1-2

在运行程序3次(2015-1-1两次,2015-1-2一次)后,我需要计算给定TransactionId给ORIGINALID的折扣百分比

因此,TransactionId 4是一个Cancallation,其OriginalId = 1.因此在select语句中我想获得该原始ID的最新有效折扣%。

select语句的输入应该是Date。例如,输入2015-1-2将返回一个记录的结果:

TransactionId, OriginalId, Discount%
4              2           45% (45% and NOT 20%) - because it's the latest discount percent given for Transactionid = 1)

1 个答案:

答案 0 :(得分:1)

您可以JOINDiscountTransactions.TransactionId = Transactions.OriginalId并使用ROW_NUMBER()获取最新的DiscountPercent

;WITH Cte AS(
    SELECT
        t.*,
        dt.DiscountPercent,
        RN = ROW_NUMBER() OVER(ORDER BY dt.Date DESC, RunId DESC)
    FROM Transactions t
    LEFT JOIN DiscountTransactions dt
        ON dt.TransactionId = t.OriginalId
    WHERE
        t.Date = CAST('20150102' AS DATE)
        AND t.Type = 'Return'
)
SELECT
    TransactionId,
    OriginalId,
    DiscountPercent
FROM Cte
WHERE RN = 1