我的数据集具有以下格式;
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 :(得分: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 server中:
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
答案 1 :(得分:0)
只需使用以下查询
首先为每个用户选择金额月份,然后选择已选择月份的数据
SELECT * FROM table WHERE amount IN (
SELECT max(amount) FROM table group by student_id
)