2011-12-07 86 views
2

我有以下表查找最近一個月和一年在不同的記錄

Name Subject  Month Year 
----- ----------- ----- ---- 
Raju History  1  2011 
Ravi Chemistry 10  2010 
Raju Computers 12  2011 
Raju Physics  10  2010 
Raju English  6  2011 
Ravi Mathematics 10  2010 
Sunil English  5  2011 
Raju History  5  2011 
Raju History  6  2011 

我想要的結果如下

Name Subject  Latest_Month_Attended Latest_Year_Attended 
----- ----------- --------------------- -------------------- 
Raju History  6      2011 
Raju Computers 12      2011 
Raju Physics  10      2010 
Raju English  6      2011 
Ravi Chemistry 10      2010 
Ravi Mathematics 10      2010 
Sunil English  5      2011 

我想找到最新的月份和年份爲一個表特別是學生和主題

請幫助我獲得上述結果

回答

3

試一下這個(編輯):

select t1.Name, t1.Subject, max(month) as Latest_Month_Attended, t2.year as Latest_Year_Attended 
from tab t1 
join (
    select Name, Subject, max(year) as year 
    from tab 
    group by Name, Subject 
) t2 on t1.name = t2.name and t1.subject = t2.subject and t1.year = t2.year 
group by t1.Name, t1.Subject, t2.year 
+0

非常感謝它是工作呢精... :) –

1
WITH 
    ranked_data AS 
(
    SELECT 
    ROW_NUMBER() OVER (PARTITION BY Name, Subject ORDER BY Year, Month) AS Rank, 
    * 
    FROM 
    yourTable 
) 
SELECT 
    * 
FROM 
    ranked_data 
WHERE 
    Rank = 1 


但是,如果年/月值只是合併成一個單一的日期字段 - 一切變得更簡單...

SELECT Name, Subject, MAX(Date) FROM yourTable GROUP BY Name, Subject 

你可以通過以下方式將日期循環至一個月:
- DATEADD(month, 0, DATEDIFF(month, 0, <any date-time>))

儘管存在相反的情況,但我的經驗通常是不要打破日期,而應將其作爲單個字段保存。

-1

一個解決方案:

select Name, Subject, Month as Latest_Month_Attended, Year as Latest_Year_Attended 
from tab 
group by Name, Subject 
having 
    max(month) and max(Year); 

結果:

Name  Subject  Latest_Month_Attended Latest_Year_Attended 
---------- ---------- --------------------- -------------------- 
Raju  Computers 12      2011     
Raju  English  6      2011     
Raju  History  6      2011     
Raju  Physics  10      2010     
Ravi  Chemistry 10      2010     
Ravi  Mathematic 10      2010     
Sunil  English  5      2011