2017-06-21 32 views
0

我的數據集具有以下格式;從Mysql中的表中選擇唯一的組合

Student_id Month Year Amount 
1   Jan 2010 600 
1   Feb 2010 391 
1   Apr 2010 673 
1   Jul 2010 564 
5   Jan 2010 789 
5   Mar 2011 298 
5   Aug 2010 347 
7   Jan 2010 654 
7   Dec 2011 621 
7   Apr 2010 450 
7   Nov 2011 980 

... &等。

我希望我的輸出將有每個唯一的id-month-year組合的最大金額。

Student_id Month Year Amount 
1   Apr 2010 673 
5   Jan 2010 789 
7   Nov 2011 980 

... &這樣子。

如何使用SQL獲取輸出?我試圖

select distinct * , MAX(Amount) from student_details; 

&

SELECT *, MAX(Amount) 
FROM student_details 
WHERE Amount IN 
(
    FROM student_details 
    GROUP BY Student_ID, Year, Month 
); 

但輸出是不理想的。

請建議協助。提前致謝。

回答

0

只需使用以下查詢

第一選擇量一個月爲每個用戶然後選擇的數據已經選擇的月份

SELECT * FROM table WHERE amount IN (
    SELECT max(amount) FROM table group by student_id 
) 
+1

不會工作如果兩名學生的金額相同,一名學生的金額最大,其他學生金額不是最大的! – Luv

1

在MySQL:

SELECT t0.* 
FROM student_details AS t0 
LEFT JOIN student_details AS t1 ON t0.Student_id=t1.Student_id t1.Amount>t0.Amount 
WHERE t1.Student_id IS NULL; 

在SQL服務器:

SELECT T.Student_id,T.Month,T.Year,T.Amount 
FROM 
(
    SELECT *,row_number() over (PARTITION BY Student_ID ORDER BY Amount DESC) as RN 
    FROM student_details 
)T 
WHERE T.RN=1