如何获取sql中每个关联者的最新工资,表也有月份和年份列。每位员工至少有4到5条记录

时间:2017-08-30 05:04:02

标签: sql-server

这是我的查询

Select distinct ASSOCIATE_ID, 
                Rate_Billed, 
                Currency, 
                RateMultiplier, 
                UOM,
                MONTH, 
                YEAR= MAX(YEAR) over (partition by associate_id) 
from  asso_billinghrs

以下是示例数据。

|ASSOCIATE_ID   |Rate_Billed |  Currency|   RateMultiplier| UOM |MONTH|YEAR|
|---------------|------------|----------|-----------------|-----|-----|----|
|1              |23.78       |USD       |1                |B    |11   |2013|
|1              |23.78       |USD       |1                |B    |2    |2014|
|1              |23.78       |USD       |1                |B    |3    |2014|
|2              |1           |INR       |0.0146701        |C    |1    |2017|
|2              |1           |INR       |0.0147451        |C    |1    |2017|

以下是输出

|ASSOCIATE_ID|  Rate_Billed|Currency|RateMultiplier|UOM|MONTH|YEAR|
|------------|-------------|--------|--------------|---|-----|----| 
|1           |23.78        |USD     |1             |B  |3    |2014|
|2           |1            |INR     |0.0147451     |C  |1    |2017|

获取具有月份和年份列的sql表中每个员工的最新薪水。每位员工至少有4到5条记录 感谢

2 个答案:

答案 0 :(得分:2)

试试这个:

WITH CTE AS(
Select distinct ASSOCIATE_ID, 
       Rate_Billed, 
       Currency, 
       RateMultiplier, 
       UOM,
       MONTH, 
       YEAR,
       ROW_NUMBER()over (partition by associate_id ORDER BY [YEAR],[MONTH] DESC) RN
from asso_billinghrs)
SELECT * 
FROM CTE 
WHERE RN=1

答案 1 :(得分:0)

您可以尝试使用RANK()获取以下输出。

 select * from 
(select *,RANK() over(partition by ASSOCIATE_ID order by tblyear desc,tblmonth desc,ratemultiplier desc)as r from asso_billinghrs)T
where r = 1

<强>输出:

    |ASSOCIATE_ID|  Rate_Billed|Currency|RateMultiplier|UOM|MONTH|YEAR|
    |------------|-------------|--------|--------------|---|-----|----| 
    |1           |23.78        |USD     |1             |B  |3    |2014|
    |2           |1            |INR     |0.0147451     |C  |1    |2017|

FIDDLE