SQL Select newest records that have distinct Name column

前端 未结 4 976
一生所求
一生所求 2020-12-12 15:30

I did search around and I found this SQL selecting rows by most recent date Which is so close to what I want but I can\'t seem to make it work.
I get an error Column \'I

相关标签:
4条回答
  • 2020-12-12 15:30
    select * from (
        Select
            ID, Name, Price, Date,
            Rank() over (partition by Name order by Date) RankOrder
        From table
    ) T
    where RankOrder = 1
    
    0 讨论(0)
  • 2020-12-12 15:42
    Select ID,Name, Price,Date
    From  temp t1
    where date = (select max(date) from temp where t1.name =temp.name)
    order by date desc
    

    Here is a SQL Fiddle with a demo of the above


    Or as Conrad points out you can use an INNER JOIN (another SQL Fiddle with a demo) :

    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 
    
    0 讨论(0)
  • 2020-12-12 15:49

    There a couple ways to do this. This one uses ROW_NUMBER. Just partition by Name and then order by what you want to put the values you want in the first position.

    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

    Note you should probably add ID (partition BY NAME ORDER BY date DESC, ID DESC) in your actual query as a tie-breaker for date

    0 讨论(0)
  • 2020-12-12 15:55

    Use Distinct instead of Group By

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

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

    0 讨论(0)
提交回复
热议问题