SQL选择具有不同Name列的最新记录

时间:2012-05-04 16:48:11

标签: sql

我做了搜索,我找到了这个 SQL selecting rows by most recent date 这与我想要的非常接近,但我似乎无法使其发挥作用 我收到错误列'ID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我希望每个Distinct Name的最新行日期

Select ID,Name,Price,Date
From  table
Group By Name
Order By Date ASC

这是我想要的一个例子

         Table
ID| Name | Price |   Date
---------------------------------
0 |  A   |  10   | 2012-05-03
1 |  B   |   9   | 2012-05-02
2 |  A   |   8   | 2012-05-04
3 |  C   |  10   | 2012-05-03
4 |  B   |   8   | 2012-05-01

期望的结果

ID| Name | Price |   Date
------------------------------
2 |  A   |   8   | 2012-05-04
3 |  C   |  10   | 2012-05-03    
1 |  B   |   9   | 2012-05-02

我正在使用microsoft sql server 2008

感谢您提供正确方向的任何帮助或要点

4 个答案:

答案 0 :(得分:52)

Select ID,Name, Price,Date
From  temp t1
where date = (select max(date) from temp where t1.name =temp.name)
order by date desc

这是一个带有演示的SQL Fiddle

或者Conrad指出你可以使用INNER JOIN:

SELECT t1.ID, t1.Name, t1.Price, t1.Date 
FROM   temp t1 
INNER JOIN 
(
    SELECT Max(date) date, name
    FROM   temp 
    GROUP BY name 
) AS t2 
    ON t1.name = t2.name
    AND t1.date = t2.date 
ORDER BY date DESC 

答案 1 :(得分:16)

有几种方法可以做到这一点。这个使用ROW_NUMBER。只需按名称进行分区,然后按照您想要的值排列在第一个位置。

WITH cte 
     AS (SELECT Row_number() OVER (partition BY NAME ORDER BY date DESC) RN, 
                id, 
                name, 
                price, 
                date 
         FROM   table1) 
SELECT id, 
       name, 
       price, 
       date 
FROM   cte 
WHERE  rn = 1 

DEMO

请注意,您可能应该在实际查询中添加ID (partition BY NAME ORDER BY date DESC, ID DESC)作为日期的平局

答案 2 :(得分:3)

select * from (
    Select
        ID, Name, Price, Date,
        Rank() over (partition by Name order by Date) RankOrder
    From table
) T
where RankOrder = 1

答案 3 :(得分:-6)

使用区别代替分组依据

Select Distinct ID,Name,Price,Date
From  table
Order By Date ASC

http://technet.microsoft.com/en-us/library/ms187831.aspx