mysql - 如何检索所有数据并将最新的数据标记为新数据?
问题描述
我有一个名为 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
任何帮助,将不胜感激!:)
解决方案
LEFT JOIN
您可以通过ing 到按andMAX(Date)
分组的列表来获得这些结果,然后检查另一个表中的值(只有最新的条目将具有非 NULL 值):StandardFamily
Standard
NULL
Date
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
推荐阅读
- java - 某些操作会产生不需要的结果
- sql - SQL Server:将特定记录导出到 xml 文件
- c - 当我使用gets时,我的C程序不会停止填充向量
- constraint-programming - 使用 minisat 解决 SAT 问题
- python - 获取列表中重复次数最多的名称,或者如果有平局,则按字母顺序排列第一个
- android - 自定义视图上的双向数据绑定自定义属性
- javascript - 为什么这个“if”语句放置有效
- postgresql - 无法从 pgadmin、CLI 连接到 IBM PostgreSQL
- azure-devops - 在 Azure DevOps 中导入工作项 .csv 文件时出错
- python-3.x - 2d python 列表populaiton