如何在sql中获取最新和第二个最近的值

时间:2014-02-04 17:20:07

标签: sql sql-server sql-server-2008

我有来自风险表

的最近和第二次最新数据表

表格中的数据如下:

RiskID        RiskName     RiskScore       RiskDate    ItemID      
1             ABC            10          23/10/2013       12            
1             ABC            8           20/12/2013       12 
1             ABC            5           15/01/2014       12
2             BC             9           19/09/2013       12
2             BC             10          17/12/2013       12
2             BC             9           12/01/2014       12

我正在寻找下面的结果,其中ItemID应为12,RiskStatus应为“Open”

R_ID   R_Name  Recent_R_Date  Recent_R_Score  Second_R_Date   Second_R_Date  ItemID
1       ABC       15/01/2014      5              20/12/2013       8           12
2       BC        12/01/2014      9             17/12/2013        10          12

寻找SQL大师的快速回复

1 个答案:

答案 0 :(得分:6)

这应该做:

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY RiskID 
                                   ORDER BY RiskDate DESC)
    FROM YourTable
)
SELECT  RiskID AS R_ID,
        RiskName AS R_Name,
        MIN(CASE WHEN RN = 1 THEN RiskDate END) AS Recent_R_Date,
        MIN(CASE WHEN RN = 1 THEN RiskScore END) AS Recent_R_Score,
        MIN(CASE WHEN RN = 2 THEN RiskDate END) AS Second_R_Date,
        MIN(CASE WHEN RN = 2 THEN RiskScore END) AS Second_R_Score
FROM CTE
GROUP BY RiskID,
         RiskName;

Here is an sqlfiddle以及此演示。结果是:

╔══════╦════════╦═══════════════╦════════════════╦═══════════════╦════════════════╗
║ R_ID ║ R_NAME ║ RECENT_R_DATE ║ RECENT_R_SCORE ║ SECOND_R_DATE ║ SECOND_R_SCORE ║
╠══════╬════════╬═══════════════╬════════════════╬═══════════════╬════════════════╣
║    1 ║ ABC    ║ 23/10/2013    ║             10 ║ 20/12/2013    ║              8 ║
║    2 ║ BC     ║ 19/09/2013    ║              9 ║ 17/12/2013    ║             10 ║
╚══════╩════════╩═══════════════╩════════════════╩═══════════════╩════════════════╝