从SQL Server中的列表中选择前1个学生费用

时间:2018-04-11 04:32:47

标签: sql sql-server

在我的SQL Server表中,我有这些数据:

+------+-----+------------+
| Name | Fee | Date_Time  |
+------+-----+------------+
| AA   | 50  | 2018-03-27 |
| AA   | 30  | 2018-04-10 |
| BB   | 40  | 2018-01-10 |
| BB   | 10  | 2018-04-10 |
| CC   | 10  | 2018-04-10 |
| DD   | 10  | 2018-04-10 |
+------+-----+------------+

如何使用TOP 1等SQL查询(AA,BB,CC,DD)ORDER BY Date_Time DESC将数据导入列表?

+------+-----+------------+
| Name | Fee | Date_Time  |
+------+-----+------------+
| AA   | 30  | 2018-04-10 |
| BB   | 10  | 2018-04-10 |
| CC   | 10  | 2018-04-10 |
| DD   | 10  | 2018-04-10 |
+------+-----+------------+

3 个答案:

答案 0 :(得分:1)

使用row_number()功能获取最高Fee

select top(1) with ties Name, Fee, Date_Time  
from table t
order by row_number() over (partition by Name order by Date_Time desc)

答案 1 :(得分:1)

另一种方法可以是

SELECT Name,Fee,Date_Time FROM
(
  SELECT *, ROW_NUMBER() OVER(PARTITION BY NAME ORDER BY DATE_TIME DESC) RN
  FROM [TABLE_NAME]
 ) T
 WHERE RN=1

如果您在特定费用的同一天有多个条目,并且您希望两者都显示,则可以使用DENSE_RANK()代替ROW_NUMBER(),如下所示。

SELECT Name,Fee,Date_Time FROM
(
  SELECT *, DENSE_RANK() OVER(PARTITION BY NAME ORDER BY DATE_TIME DESC) RN
  FROM [TABLE_NAME]
 ) T
 WHERE RN=1

<强> DEMO

答案 2 :(得分:0)

根据row_number的分区提供Name,然后按Date_Time的降序排序,然后选择row_number为1的行。

<强>查询

;with cte as (
    select [rn] = row_number() over(
        partition by [Name]
        order by [Date_Time] desc
    ), *
    from [your_table_name]
)
select [Name], [Fee], [Date_Time]
from cte
where [rn] = 1;