MariaDB/Mysql SELECT 从 - 到子查询
MariaDB/Mysql SELECT from - to with Subquery
我有一个 table 'Device' 安装日期和客户:
Id
DeviceName
Installed
Customer
1
A
2021-10-10
1
2
B
2021-10-10
1
3
A
2021-10-20
2
4
A
2021-10-30
3
我需要以下结果
DeviceName
InstalledFrom
InstalledTo
Customer
A
2021-10-10
2021-10-20
1
B
2021-10-10
NULL
1
A
2021-10-20
2021-10-30
2
A
2021-10-30
NULL
3
尝试了以下SQL
select a.DeviceName, a.Installed as InstalledFrom, b.installed as InstalledTo, a.customer
from Device a
left outer join Device b on ( b.DeviceName = ( SELECT DeviceName
FROM Device
where DeviceName = a.DeviceName
AND Installed > a.Installed
order by installed limit 1) )
但这并没有给出预期的结果。
感谢您的帮助!
测试一下:
SELECT t1.DeviceName,
t1.Installed InstalledFrom,
t2.Installed InstalledTo,
t1.Customer
FROM Device t1
LEFT JOIN Device t2 ON t1.DeviceName = t2.DeviceName
AND t1.Installed < t2.Installed
WHERE NOT EXISTS ( SELECT NULL
FROM Device t3
WHERE t1.DeviceName = t3.DeviceName
AND t1.Installed < t3.Installed
AND t3.Installed < t2.Installed )
我有一个 table 'Device' 安装日期和客户:
Id | DeviceName | Installed | Customer |
---|---|---|---|
1 | A | 2021-10-10 | 1 |
2 | B | 2021-10-10 | 1 |
3 | A | 2021-10-20 | 2 |
4 | A | 2021-10-30 | 3 |
我需要以下结果
DeviceName | InstalledFrom | InstalledTo | Customer |
---|---|---|---|
A | 2021-10-10 | 2021-10-20 | 1 |
B | 2021-10-10 | NULL | 1 |
A | 2021-10-20 | 2021-10-30 | 2 |
A | 2021-10-30 | NULL | 3 |
尝试了以下SQL
select a.DeviceName, a.Installed as InstalledFrom, b.installed as InstalledTo, a.customer
from Device a
left outer join Device b on ( b.DeviceName = ( SELECT DeviceName
FROM Device
where DeviceName = a.DeviceName
AND Installed > a.Installed
order by installed limit 1) )
但这并没有给出预期的结果。
感谢您的帮助!
测试一下:
SELECT t1.DeviceName,
t1.Installed InstalledFrom,
t2.Installed InstalledTo,
t1.Customer
FROM Device t1
LEFT JOIN Device t2 ON t1.DeviceName = t2.DeviceName
AND t1.Installed < t2.Installed
WHERE NOT EXISTS ( SELECT NULL
FROM Device t3
WHERE t1.DeviceName = t3.DeviceName
AND t1.Installed < t3.Installed
AND t3.Installed < t2.Installed )