如何在SQL Server中获取最新和最近的值

时间:2014-02-05 05:09:14

标签: sql sql-server sql-server-2008-r2 sql-server-2012

我有包含与风险相关的数据的表格,我必须从风险表中获取最新和第二个最近的第二个数据

表格中的数据如下:

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

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

2 个答案:

答案 0 :(得分:3)

修改

由于您已使用sql-server-2012标记,因此您可以访问LEAD和LAG分析函数,这样您就可以“查看”其他行。我还假设你需要'{分区'RiskName

SELECT TOP 2
    RiskId, RiskName, RiskDate AS Recent_R_Date, RiskScore AS Recent_R_Score, 
    LAG(RiskDate) OVER (PARTITION BY RiskName ORDER BY RiskDate ASC) AS Second_R_Date,
    LAG(RiskScore) OVER (PARTITION BY RiskName ORDER BY RiskDate ASC) AS Second_R_Score,
    ItemID
 FROM Risk
 WHERE ItemID = 12
 ORDER BY RiskDate DESC;

Fiddle here

<德尔> 它应该像按日期排序DESC一样简单,然后将结果限制为2,即:     选择TOP 2         R_ID,R_Name,Recent_R_Date,Recent_R_Score,         Second_R_Date,Second_R_Date,ItemID      来自风险      WHERE ItemID = 12      ORD BY RiskDate DESC;

答案 1 :(得分:3)

一种方法(也适用于SQL Server 2008)

SELECT RiskID, RiskName,
       MAX(CASE WHEN rnum = 1 THEN RiskDate END) RecentDate,
       MAX(CASE WHEN rnum = 1 THEN RiskScore END) RecentScore,
       MAX(CASE WHEN rnum = 2 THEN RiskDate END) SecondDate,
       MAX(CASE WHEN rnum = 2 THEN RiskScore END) SecondScore,
       ItemID
  FROM
(
  SELECT *, ROW_NUMBER() OVER (PARTITION BY RiskID ORDER BY RiskDate DESC) rnum
    FROM Risk
   WHERE ItemID = 12
) q
 WHERE rnum <= 2
 GROUP BY ItemID, RiskID, RiskName
 ORDER BY RiskID

输出:

| RISKID | RISKNAME | RECENTDATE | RECENTSCORE | SECONDDATE | SECONDSCORE | ITEMID |
|--------|----------|------------|-------------|------------|-------------|--------|
|      1 |      ABC | 2014-01-15 |           5 | 2013-12-20 |           8 |     12 |
|      2 |       BC | 2014-01-12 |           9 | 2013-12-17 |          10 |     12 |

这是 SQLFiddle 演示