如何从组中获取具有最大日期的行?

时间:2016-08-18 22:25:34

标签: sql-server

Table1    
Id, CatygoryId, Name, DataCreate

我希望将这些数据分组并从具有最大DataCreate的组行中获取

示例

Id   CatygoryId   Name   DataCreate

1       1         Name1  10/08/2016
2       1         Name2  11/08/2016
3       1         Name3  12/08/2016
4       1         Name4  13/08/2016
5       2         Name5  18/08/2016
6       2         Name6  19/08/2016

在查询结果中我想要

4       1         Name4  13/08/2016
6       2         Name6  19/08/2016

3 个答案:

答案 0 :(得分:0)

select max(Id), CatygoryId, max(Name), max(DataCreate) 
from Table1
group by CatygoryId   

答案 1 :(得分:0)

试试这个

CREATE TABLE #TEMP_TABLE(ID INT, CatygoryId  INT, Name   VARCHAR(30), DataCreate DATE)

INSERT INTO #TEMP_TABLE

SELECT 1,       1,         'Name1',  '08/10/2016' UNION ALL
SELECT 2,       1,         'Name2',  '08/11/2016' UNION ALL
SELECT 3,       1,         'Name3',  '08/12/2016' UNION ALL
SELECT 4,       1,         'Name4',  '08/13/2016' UNION ALL
SELECT 5,       2,         'Name5',  '08/18/2016' UNION ALL
SELECT 6,       2,         'Name6',  '08/19/2016' 


;WITH T1
AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY CatygoryId ORDER BY DataCreate DESC) ROW_NO, * 
    FROM #TEMP_TABLE
)
SELECT *
FROM T1
WHERE T1.ROW_NO=1

答案 2 :(得分:-1)

看起来你想按ID分组。您还想要最近的日期,还是最高(2,3等)记录?

顺便说一句,我想你可能想要考虑这样的事情,但是需要将日期格式更改为'yyyymmdd'(更容易找到最大/最近)

考虑到你有yyyymmdd格式:

表1
Id,CatygoryId,Name,DataCreate

查询:

Select Id, Name, CategoryId, DateCreated from Table1
Where DateCreate = (Select MAX(DateCreated) from Table1)
Group by Id

注意:这将为您提供最新日期的所有记录,请记住考虑到您有yyyymmdd年份格式,我建议。

现在,如果你想要的不仅仅是第一条记录。 请使用yyyymmdd格式考虑此查询:

Select Id, Name, CategoryId, DateCreated from Table1
Where DateCreate = (Select top (# of rows you would like to return) Datecreated from Table1 

Order by DateCreated Desc)
Group by Id