获取存储数据增量的表的最新记录?

时间:2012-04-13 23:12:08

标签: sql-server tsql

我有一张表Actions,图示打击:

[Actions]
ActionID
Date
Status <--Nullable, a delta column, only stores value when status changes

现在我想要检索最新记录,但是该记录的Stutus很可能为空,因此我希望得到其最后一次状态更改(按Date排名)。

以下是一个例子:

ActionID | Date | Status
------------------------
1        | 04/12| 'Bon'
2        | 04/13| NULL
3        | 04/14| NULL
4        | 04/15| NULL

我的最新记录应如下:ActionID: 4Date: 04/15Status: 'Bon'

我知道可以使用嵌套的select语句,但在我的真实表格中,我有大约10个这样的列,当这些列的大量查询产生时,它将极大地影响性能。我想知道是否有更简单的方法吗?

2 个答案:

答案 0 :(得分:0)

不确定我是否理解你的规则,但试试这个:

SELECT TOP 1
ActionID,
Date,
(SELECT TOP 1 Status FROM Actions WHERE Status IS NOT NULL ORDER BY ActionID DESC) AS Status
FROM Actions
ORDER BY ActionID DESC

你说你有10列..它是如何工作的?

与方案A)相似

 ActionID | Date  | StatusA | StatusB | StatusC
        1 | 04/11 | DELTA_A | NULL    | DELTA_C
        2 | 04/12 | NULL    | DELTA_B | DELTA_C
        3 | 04/13 | DELTA_A | NULL    | NULL 

..那么多个SELECT TOP 1子查询仍然是我认为最好的选择..

但如果它像情景B)

 ActionID | Date  | StatusA | StatusB | StatusC
        1 | 04/11 | NULL    | NULL    | NULL
        2 | 04/12 | DELTA_A | DELTA_B | DELTA_C
        3 | 04/13 | NULL    | NULL    | NULL 

..那么你可以像这样“反转”你的查询:

SELECT TOP 1
(SELECT TOP 1 ActionID FROM Actions WHERE Status IS NOT NULL ORDER BY ActionID DESC) AS ActionID,
(SELECT TOP 1 Date FROM Actions WHERE Status IS NOT NULL ORDER BY ActionID DESC) AS Date,
StatusA,
StatusB,
StatusC
FROM Actions
WHERE StatusA IS NOT NULL -- then StatusB and StatusC are also NOT NULL
ORDER BY ActionID DESC

..但请注意,如果没有StatusA = NOT NULL的行,则可能会得到空结果。

答案 1 :(得分:0)

也许这有助于你,虽然我不确定我是否理解你的要求:

WITH Actions AS(
   SELECT ROW_NUMBER()OVER(Order By Date DESC)AS DateRank
        , ActionsID
        , Date
        , Status
    FROM [Actions]
)
SELECT TOP 1 a1.ActionsID,a1.Date,a2.Status 
FROM Actions a1 INNER JOIN Actions a2 
    ON a1.DateRank < a2.DateRank AND a2.Status IS NOT NULL
WHERE a1.DateRank=1