按最新日期每月选择1条不同的记录

时间:2014-07-31 11:15:33

标签: sql sql-server

我有一个如下所示的数据列表:

 Name        Date           Weight 
Person 1    01/01/2014       89KG
Person 2    01/01/2014       62KG
Person 1    07/01/2014       88KG
Person 2    07/01/2014       62KG
Person 1    21/01/2014       85KG
Person 2    21/01/2014       63KG

我想要做的是仅选择具有不同名称的记录,并且是给定月份中的最新日期。因此,对于此示例,我只想选择21/01/2014的人1和人2记录(因为这是最新日期)。我正在使用SQL 2008。

3 个答案:

答案 0 :(得分:1)

请尝试使用DENSE_RANK

select 
  * 
From (
    select 
        *, 
        DENSE_RANK() over(PARTITION BY YEAR([Date]), 
                                     MONTH([Date]) 
                         ORDER BY [Date] desc) Rnk
    From tbl
)x where Rnk=1

答案 1 :(得分:1)

请查看这是否适合您。

示例数据:

IF OBJECT_ID(N'tempdb..#TEMP') > 0
    BEGIN
       DROP TABLE #TEMP
    END

CREATE TABLE #TEMP(Name VARCHAR(20),
                WDate VARCHAR(20),
                Weight VARCHAR(20))
INSERT INTO #TEMP
VALUES
('Person 1', '01/01/2014', '89KG'),
('Person 2', '01/01/2014', '62KG'),
('Person 1', '07/01/2014', '88KG'),
('Person 1', '07/01/2014', '88KG'),
('Person 2', '07/02/2014', '62KG'),
('Person 1', '21/01/2014', '85KG'),
('Person 2', '21/01/2014', '63KG');

<强>脚本:

;WITH cte_DateFormat
    AS (
    SELECT Name,
         CONVERT(DATE, WDate, 103) AS WDate,
         Weight
    FROM #TEMP
    )
, cte_Rank
    AS (
    SELECT ROW_NUMBER() OVER (PARTITION BY Name,
                                   CAST(YEAR(WDate) AS VARCHAR(4)) + CAST(MONTH(WDate) AS VARCHAR(2)) ORDER BY WDate DESC) AS ID,
         Name,
         WDate,
         Weight
    FROM cte_DateFormat
    )
    SELECT Name,
         WDate,
         Weight
    FROM cte_Rank
    WHERE ID = 1

清理脚本:

IF OBJECT_ID(N'tempdb..#TEMP') > 0
    BEGIN
       DROP TABLE #TEMP
    END

答案 2 :(得分:1)

这也可以使用行分区:

SELECT Name, Date, Weight
FROM (  SELECT
            Name, 
            Date, 
            Weight, 
            ROW_NUMBER() OVER ( PARTITION BY Name, MONTH(Date) 
                                ORDER BY Date DESC) AS [RowNum]
        FROM [YourTableHere]
        ) Tbl
WHERE Tbl.RowNum = 1
ORDER BY MONTH(Date), Name

测试脚本:

DECLARE @Table TABLE (Name VARCHAR(20), Date Date, Weight VARCHAR(20))
INSERT INTO @Table (Name, Date, Weight)
VALUES  ('Person 1', '1/1/2014', '89KG'),
        ('Person 2', '1/1/2014', '62KG'),
        ('Person 1', '1/7/2014', '88KG'),
        ('Person 2', '1/7/2014', '62KG'),
        ('Person 1', '1/21/2014', '85KG'),
        ('Person 2', '1/21/2014', '63KG'),
        ('Person 1', '2/1/2014', '84KG'),
        ('Person 2', '2/1/2014', '61KG'),
        ('Person 1', '2/11/2014', '83KG'),
        ('Person 2', '2/11/2014', '60KG')

SELECT Name, Date, Weight
FROM (  SELECT
            Name, 
            Date, 
            Weight, 
            ROW_NUMBER() OVER ( PARTITION BY Name, MONTH(Date) 
                                ORDER BY Date DESC) AS [RowNum]
        FROM @Table
        ) Tbl
WHERE Tbl.RowNum = 1
ORDER BY MONTH(Date), Name