SQL:按日期排序和不同的数字而不丢失字段

时间:2018-02-16 08:39:54

标签: sql sql-server sql-server-2005

我对SQL的了解不是最好的,但我需要一个快速的解决方案。我有一张桌子

number     | date       | text

1          | 2018-01-13 | A

2          | 2018-01-15 | B

1          | 2018-02-15 | C

现在我需要根据日期删除输出(select)中的重复值“number”。它应该是这样的:

number     | date       | text

2          | 2018-01-15 | B

1          | 2018-02-15 | C

我试过

SELECT DISTINCT number, date ORDER BY date DESC FROM table

问题是我现在错过输出中的字段“text”。我也试过

SELECT * DISTINCT(SELECT * number ORDER BY(date) DESC) FROM table

有什么想法吗?

4 个答案:

答案 0 :(得分:4)

一个选项使用ROW_NUMBER

SELECT number, date, text
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY number ORDER BY date DESC) rn
    FROM yourTable
) t
WHERE rn = 1;

答案 1 :(得分:2)

您可以使用以下查询来实现:

SELECT t1.number, t1.date, t1.text
FROM yourTable t1
INNER JOIN
(
     SELECT number, MAX(date) AS max_date
     FROM yourTable
     GROUP BY number
) t2
    ON t1.number = t2.number AND
       t1.date = t2.max_date;

答案 2 :(得分:1)

使用以下查询,这将适用于您的要求

选择号码,日期,文字 从 (     SELECT *,ROW_NUMBER()OVER(PARTITION BY number ORDER BY date DESC)rn     从测试 )t 在哪里rn = 1;

答案 3 :(得分:0)

只需使用窗口函数即可完成:

create table #TEST ([NUMBER] int, [DATE] date, [TEXT] char(1))

insert into #TEST values (1, '2018-01-13', 'A'), (2, '2018-01-15', 'B'), (1, '2018-02-15', 'C')

SELECT DISTINCT [NUMBER]
    , FIRST_VALUE([DATE]) OVER (PARTITION BY [NUMBER] ORDER BY [DATE] DESC) AS [DATE]
    , FIRST_VALUE([TEXT]) OVER (PARTITION BY [NUMBER] ORDER BY [DATE] DESC) AS [TEXT]
 FROM #TEST