mysql - 如何比较MySql中的初始记录和最新记录
问题描述
我试图在同一个查询中加入以下三个表,并尝试获取初始值和最终值的状态基础。
表格1
ID1 Date1 Value1
T-1 2019-12-15 12:14:13 10000
T-2 2019-12-15 16:17:24 11000
T-3 2019-12-17 10:01:11 15000
T-4 2019-12-18 21:10:21 17000
表2
ID2 Date2 Value2 Seq
T-1 2019-12-16 19:18:11 10000 1
T-2 2019-12-16 16:33:24 12000 1
T-2 2019-12-17 15:21:21 12000 2
T-2 2019-12-17 13:10:18 18000 3
T-2 2019-12-18 19:18:07 11000 4
T-3 2019-12-17 11:11:11 14000 1
T-3 2019-12-18 22:18:08 13000 2
T-3 2019-12-18 19:07:01 13000 3
T-4 2019-12-19 21:38:15 17000 1
T-4 2019-12-19 21:45:20 17000 2
表3
ID3 Date3 Value3
T-1 2019-12-16 19:18:11 10000
T-2 2019-12-18 19:18:07 11000
T-3 2019-12-18 19:07:01 13000
T-4 2019-12-19 21:45:20 17000
很明显Table3
包含最新记录,我想使用上表得出以下详细信息:
- 如果
Value2
whereSeq
=1 小于或大于Value1
则显示为 FALSE - 获取初始日期,其中
Seq
=1 和每个唯一日期的最新日期ID
所需输出:
ID3 Value1 Value3 Initial_Date Latest_Date Status
T-1 10000 10000 2019-12-16 19:18:11 2019-12-16 19:18:11 TRUE
T-2 11000 12000 2019-12-16 16:33:24 2019-12-18 19:18:07 FALSE
T-3 15000 14000 2019-12-17 11:11:11 2019-12-18 19:07:01 FALSE
T-4 17000 17000 2019-12-19 21:38:15 2019-12-19 21:45:20 TRUE
我尝试了以下查询,但没有成功: MySQL 版本是5.7.25
select ID3,Value1, Value2, Date2 As Initial_Date, Date3 As Final_Date
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3ID3
where t2.Seq=1
group by t3.ID3;
解决方案
对于此示例数据,您只需group by
从查询中删除子句和Status
列,如下所示:
select t3.ID3, t1.Value1, t2.Value2,
t2.Date2 As Initial_Date, t3.Date3 As Final_Date,
t1.Value1 = t2.Value2 Status
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3.ID3
where t2.Seq = 1
如果您希望Status
列为TRUE
or FALSE
:
select t3.ID3, t1.Value1, t2.Value2,
t2.Date2 As Initial_Date, t3.Date3 As Final_Date,
case when t1.Value1 = t2.Value2 then 'TRUE' else 'FALSE' end Status
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3.ID3
where t2.Seq = 1
请参阅演示。
结果:
> ID3 | Value1 | Value2 | Initial_Date | Final_Date | Status
> :-- | -----: | -----: | :------------------ | :------------------ | :-----
> T-1 | 10000 | 10000 | 2019-12-16 19:18:11 | 2019-12-16 19:18:11 | TRUE
> T-2 | 11000 | 12000 | 2019-12-16 16:33:24 | 2019-12-18 19:18:07 | FALSE
> T-3 | 15000 | 14000 | 2019-12-17 11:11:11 | 2019-12-18 19:07:01 | FALSE
> T-4 | 17000 | 17000 | 2019-12-19 21:38:15 | 2019-12-19 21:45:20 | TRUE
另外,既然你有where t2.Seq = 1
那么到 Table2 的连接是一个内连接,而不是一个左连接。
推荐阅读
- python - 带有选项按钮的双重回调
- python - 谷歌语音转文本时间戳是连续的,但口语之间有间隔
- c# - 如何通过代码在 Windows 窗体中创建对象?
- maven - 处理 Parent pom 时遇到问题
- angular - Webpack Bundle Analyzer 不适用于 Jhipster Angular 应用程序
- python - python枕头包在Rstudio中不起作用
- javascript - 从平面到嵌套对象递归javascript
- python - 第一个 Flask 单元测试成功,所有后续测试都失败。也许是陈旧的 app_context?
- ios - Swift Firebase 观察 .childAdded 对现有项目而不是新项目做出反应
- c# - 可以转换为有效日期时间的最长字符串是多少?