首页 > 解决方案 > 如何检索所有数据并将最新的数据标记为新数据?

问题描述

我有一个名为 Standards 的表,其中包括 ID、StandardsFamiliy、Standards、Date 和 Link。我想显示所有数据,但我希望同一 StandardsFamily 和 Standards 中的最新日期标记为最新日期。例如,如果我有

StandardFamily,  Standards, Date
A                   a        2018
A                   a        2017
B                   b        2016
C                   c        2010
C                   c        2011
C                   c        2011
C                   c2       2018

我想检索这个:

StandardFamily,  Standards, Date,  Status
A                   a        2018   New
A                   a        2017   Old
B                   b        2016   New
C                   c        2010   Old
C                   c        2011   Old
C                   c        2012   New
C                   c2       2018   New

我知道如何使用以下查询仅检索最新的:

select * 
from Standards
where (StandardFamily,Standards,Date) 
IN (select StandardFamily,Standards,Max(Date) from Standards group by StandardFamily,Standards)

我想我可能会遵循类似的东西

select
case when (...) then "New" else "Old" end
from Table

任何帮助,将不胜感激!:)

标签: mysqlsql

解决方案


LEFT JOIN您可以通过ing 到按andMAX(Date)分组的列表来获得这些结果,然后检查另一个表中的值(只有最新的条目将具有非 NULL 值):StandardFamilyStandardNULLDate

SELECT *,
    CASE WHEN s1.StandardFamily IS NULL THEN "Old" ELSE "New" END AS Status
FROM Standards s
LEFT JOIN (SELECT StandardFamily, Standards, MAX(Date) AS Date
           FROM Standards
           GROUP BY StandardFamily, Standards) s1 ON s1.StandardFamily = s.StandardFamily AND s1.Standards = s.Standards AND s1.Date = s.Date

输出:

StandardFamily  Standards   Date    Status
A               a           2018    New
A               a           2017    Old
B               b           2016    New
C               c           2010    Old
C               c           2011    Old
C               c           2012    New
C               c2          2018    New

dbfiddle 上的演示


推荐阅读