即使MAX不同,如何获得MAX结果

时间:2013-09-04 17:29:27

标签: sql sql-server

我有一个代码,我提取语言知识,每个员工都有一个计划年度,他们并非每年都完成它们,为了获得他们最近的一个,我使用MAX计划年度。现在的标准之一是他们是否愿意在海上移动,问题出现了它将提出他们最近的YES和最近的NO而我只需要他们最近的计划年度是否是或不,我我很难排除故障。代码如下:

SELECT Employee_ID, Accept_International_Assignment, MAX(Plan_Year) AS Expr1
FROM  dbo.v_sc08_CD_Employee_Availabilities
GROUP BY Employee_ID, Accept_International_Assignment    

4 个答案:

答案 0 :(得分:4)

我怀疑这会比公认的答案更有效......

;WITH x AS 
(
  SELECT Employee_ID, Accept_International_Assignment, Plan_Year,
    rn = ROW_NUMBER() OVER (PARTITION BY Employee_ID ORDER BY Plan_Year DESC)
  FROM dbo.v_sc08_CD_Employee_Availabilities -- who comes up with these names?
)
SELECT Employee_ID, Accept_International_Assignment, Plan_Year
  FROM x WHERE rn = 1;

答案 1 :(得分:2)

SELECT a.Employee_ID, a.Accept_International_Assignment, a.Plan_Year
FROM  dbo.v_sc08_CD_Employee_Availabilities a
INNER JOIN (SELECT Employee_ID, MAX(Plan_Year) maxPlanYear
            from dbo.v_sc08_CD_Employee_Availabilities
            GROUP BY Employee_ID) m
   ON a.Plan_Year = m.maxPlanYear AND a.Employee_ID = m.Employee_ID

答案 2 :(得分:0)

我不确定你是否只想要拉斐尔发布的最新决定和年份,或者如果你想要的是“是”和“否”,但总是在那个员工的最大计划年度。

以下是对是和否的查询,但最高计划年度始终是员工的最大值。

select main.Employee_ID, Accept_International_Assignment, Expr1
from (
    SELECT Employee_ID, Accept_International_Assignment
    FROM  @v_sc08_CD_Employee_Availabilities
    GROUP BY Employee_ID, Accept_International_Assignment  
) main
inner join
(
 select Employee_ID, MAX(Plan_Year) as Expr1
 from @v_sc08_CD_Employee_Availabilities
 group by Employee_ID) empPlanYear
on main.Employee_ID = empPlanYear.Employee_ID

答案 3 :(得分:-2)

你需要在max()上加一个子查询并加入。(/ p>)

SQL Group by & Max