Access SQL query: find the row with the most recent date for each distinct entry in a table

后端 未结 5 1849
盖世英雄少女心
盖世英雄少女心 2021-02-06 08:50

All,

I\'m sure this is a pretty simple SQL query question, but I\'m sure there\'s a good way, and a very BAD way, to do this. Left to my own devices, I\'m liable to end

相关标签:
5条回答
  • 2021-02-06 09:03

    I think what you're looking for is this:

    select id, value, as_of from table_name where as_of = max(as_of) group by id

    This says for each id, find the max as_of, and get that value.

    This is generic sql. I'm not sure about access. I'm sure if this doesn't work there is something similar.

    Good luck! Joe

    0 讨论(0)
  • 2021-02-06 09:16

    Not sure what platform you're looking to do this on, but in T-SQL you can do the following:

    SELECT t.*
    FROM (
        SELECT ID, MAX(As_Of) as r1
        FROM myTable
        GROUP BY ID
        ) as dt
    INNER JOIN myTable t ON dt.ID = t.ID and dt.r1 = t.As_Of
    

    Good luck!

    EDIT: Well my poor answer was bothering me so i've fixed it, even though this answer already exists elsewhere on the page now.

    0 讨论(0)
  • 2021-02-06 09:21

    If you need both the date and the value, you need to do a join:

    SELECT ID, Value,As_of 
    from yourTable a inner join 
              (SELECT ID, MAX(As_of) as As_of 
              from yourTable group by ID) b 
    on a.ID=b.ID and a.As_of = b.As_of
    
    0 讨论(0)
  • 2021-02-06 09:21

    @Funka, that will not work if you have duplicate "value" values for different ID's - that will basically give you a grouped list by "value", not by id...

    @Joe Fair, aggregates aren't allowed in where clauses without a subquery/having combo as well, at least not in ANSI...

    This will give you the list, but will give duplicates as well if you have multiple rows with the same id/As_of values:

    select  t1.id, t1.value, t1.As_of
    from    tableName t1
    join    (
            select  id as id, max(As_of) as max_as_of
            from    tableName
            group by id
        ) t2
    on      t1.id = t2.id
    and     t1.As_of = t2.max_as_of
    

    If you want to remove duplicates from that, you'd just want to add a distinct to the top select, like this:

    select  distinct t1.id, t1.value, t1.As_of
    from    tableName t1
    join    (
            select  id as id, max(As_of) as max_as_of
            from    tableName
            group by id
        ) t2
    on      t1.id = t2.id
    and     t1.As_of = t2.max_as_of
    
    0 讨论(0)
  • 2021-02-06 09:26

    Try something like this

    SELECT t1.*
    FROM (SELECT Table1.ID, Max(Table1.As_Of) AS MaxOfAs_Of
    FROM Table1
    GROUP BY Table1.ID
    )  AS MaxIDS INNER JOIN Table1 t1 ON MaxIDS.ID = t1.ID
    and MaxIDS.MaxOfAs_Of = t1.As_Of
    
    0 讨论(0)
提交回复
热议问题