我试图在同一个查询中连接以下三个表,并试图获取状态基础的初始值和最终值。
Table1
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 17000Table2
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 2Table3
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中Seq=1小于或大于Value1,则将其显示为FALSESeq=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;发布于 2019-12-21 18:08:27
对于这个示例数据,您所要做的就是从查询中删除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或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的连接是内部连接,而不是左连接。
https://stackoverflow.com/questions/59438452
复制相似问题