如何按月和业务领域选择最终价值?

时间:2017-07-21 14:17:30

标签: sql sql-server tsql

我有下表,我想根据业务范围仅选择上个月。

这些原始表:

fk_month    fk_business_area
201706       8
201707       25
201707       27
201707       9
201707       8
201707       28
201707       26
201708       9

选择后,我想要这个结果:

fk_month    fk_business_area
201707      25
201707      27
201707      8
201707      28
201707      26
201708      9

问候。

2 个答案:

答案 0 :(得分:5)

你可以做一个MAX()聚合:

Select   Max(fk_month) As fk_month,
         fk_business_area
From     TheseOriginalTable
Group By fk_business_area

您还可以使用窗口函数查找最新的函数:

;With Cte As
(
    Select  *,
            Row_Number() Over (Partition By fk_business_area Order By fk_month Desc) RN
    From    TheseOriginalTable
)
Select  fk_month, fk_business_area
From    Cte
Where   RN = 1

答案 1 :(得分:1)

Siyual回答是正确的方法,但如果除了提到的那个之外还有其他任何专栏,那么使用Row_Number窗函数

select top 1 with ties *
from yourtable 
order by row_number()over(partition by fk_business_area order by fk_month desc)