选择具有最新可用数据和上个月的月份

时间:2017-12-20 16:24:43

标签: sql-server

我的表格在结构上类似于下面定义的表格。 PK是前4列,最后一列是实际得分。每一行都在本财政年度的12个月内完全填充,分数将在当月可用时填写。每个月,我们都想报告最新的可用分数(一些分数落后一两个月,因此我们无法使用当前月份)以及之前的分数。鉴于下面提供的数据,我希望结果如下:

+--------+--------+--------+-----------+----------+---------------+
|ScoreKey|DeptName|TestName|ScorePeriod|ScoreValue|CurrentPrevious|
+--------+--------+--------+-----------+----------+---------------+
|    1   |  'abc' |  'def' |  201707   |   1      |   Current     |
|    1   |  'abc' |  'def' |  NULL     |   NULL   |   Previous    |
|    2   |  'abc' |  'def' |  201801   |   7      |   Current     |
|    2   |  'abc' |  'def' |  201712   |   6      |   Previous    |
+--------+--------+--------+-----------+----------+---------------+

我尝试使用GROUP BY然后MAX()执行UNION并过滤掉MAX值但不考虑只有一行数据的值(它不返回任何行。)

提供表格和值的代码:

    create table #scores (
        ScoreKey INT,
        DeptName VARCHAR(10),
        TestName VARCHAR(10),
        ScorePeriod INT,
        ScoreValue INT
    )

    insert into #scores values (1,'abc','def',201707,1)
    insert into #scores values (1,'abc','def',201708,NULL)
    insert into #scores values (1,'abc','def',201709,NULL)
    insert into #scores values (1,'abc','def',201710,NULL)
    insert into #scores values (1,'abc','def',201711,NULL)
    insert into #scores values (1,'abc','def',201712,NULL)
    insert into #scores values (1,'abc','def',201801,NULL)
    insert into #scores values (1,'abc','def',201802,NULL)
    insert into #scores values (1,'abc','def',201803,NULL)
    insert into #scores values (1,'abc','def',201804,NULL)
    insert into #scores values (1,'abc','def',201805,NULL)
    insert into #scores values (1,'abc','def',201806,NULL)
    insert into #scores values (2,'abc','def',201707,1)
    insert into #scores values (2,'abc','def',201708,3)
    insert into #scores values (2,'abc','def',201709,4)
    insert into #scores values (2,'abc','def',201710,5)
    insert into #scores values (2,'abc','def',201711,5)
    insert into #scores values (2,'abc','def',201712,6)
    insert into #scores values (2,'abc','def',201801,7)
    insert into #scores values (2,'abc','def',201802,NULL)
    insert into #scores values (2,'abc','def',201803,NULL)
    insert into #scores values (2,'abc','def',201804,NULL)
    insert into #scores values (2,'abc','def',201805,NULL)
    insert into #scores values (2,'abc','def',201806,NULL)

1 个答案:

答案 0 :(得分:0)

select * 
from 
( select * 
       , row_number over (partition by ScoreKey, DeptName, TestName order by ScorePeriod desc) as rn
  from table 
) aa
where rn <= 2