根据月份获取最新日期值

时间:2017-05-05 13:24:17

标签: sql sql-server tsql

我有以下记录。它基于用户名,日期和测试核心而被破坏。

Username     date                          testscore
mike         2016-11-30 23:41:10.143       1
mike         2016-11-27 23:41:11.143       12
mike         2016-11-24 23:41:11.143       16
john         2016-11-28 23:41:11.143       7
john         2016-11-25 23:42:11.143       12
john         2016-11-25 23:42:11.143       7
mike         2016-10-30 23:41:10.143       1
mike         2016-10-27 23:41:11.143       5
mike         2016-10-24 23:41:11.143       16
john         2016-10-28 23:41:11.143       12
john         2016-10-25 23:42:11.143       8
john         2016-10-24 23:42:11.143       2

对于每个用户,我希望获得按月分类的最新测试分数(月份)。换句话说,我想获得给定年份每个用户每月的最后得分。

所以对于上面的内容,它将是

username       date                        testscore
mike           2016-11-30 23:41:10.143     1
john           2016-11-28 23:41:11.143     7 
mike           2016-10-30 23:41:10.143     1
john           2016-10-28 23:41:11.143     12

4 个答案:

答案 0 :(得分:3)

或许使用 WITH TIES 子句与 Row_Number()

一起使用
Select top 1 with ties * 
 from YourTable
 Order by Row_Number() over (partition by UserName,year(date),month(date) order by date desc)

返回

Username    date                    testscore
john        2016-10-28 23:41:11.143 12
john        2016-11-28 23:41:11.143 7
mike        2016-10-30 23:41:10.143 1
mike        2016-11-30 23:41:10.143 1

答案 1 :(得分:2)

您可以使用ROW_NUMBER()

WITH CTE AS
(
    SELECT *,
           RN = ROW_NUMBER() OVER(PARTITION BY username, CONVERT(VARCHAR(6),[date],112)
                                  ORDER BY [date] DESC)
    FROM dbo.YourTable
)
SELECT *
FROM CTE 
WHERE RN = 1;

答案 2 :(得分:0)

这个怎么样:

select top 1 from <mytable> group by date.year(),date.month(),username order by date;

答案 3 :(得分:-1)

您似乎需要一个主键,但您仍然可以完成工作。

基本上,您希望每个用户名的行对应于该用户的最新日期。

SELECT username, date, testscore
FROM MyTable m1
WHERE m1.date = (SELECT MAX(m2.DATE)) 
                 FROM MyTable m2 
                 WHERE m2.username = m1.username)