挣扎着一些sql,会很感激一些指导。
有两个表日志和感知
日志 -
assetid ts nodeid status
1 2017-10-26 14:00:10 73 240
2 2017-10-26 14:00:06 21 160
3 2017-10-26 14:00:04 18 230
4 2017-10-26 14:00:02 19 400
5 2017-10-26 14:00:00 21 190
1 2017-10-26 13:20:08 18 20
2 2017-10-26 13:06:10 20 160
3 2017-10-26 13:03:04 17 230
感觉 -
status value
20 5
160 37
190 39
230 56
240 58
400 90
尝试找到正确的语法,只显示每个assetid的最新记录(在datetime中),然后从sense表中显示相应的值(基于两个表中的匹配状态)来生成 -
assetid ts nodeid status value
1 2017-10-26 14:00:10 73 240 58
2 2017-10-26 14:00:06 21 160 37
3 2017-10-26 14:00:04 18 230 56
4 2017-10-26 14:00:02 19 400 90
5 2017-10-26 14:00:00 21 190 39
尝试过 -
Select assetid, ts, nodeid, status, value
From
logs
Join sense X on X.status = logs.status
Group by assetid
Order by ts DESC
但这只输出1行(而不是5)
assetid ts nodeid status value
1 2017-10-26 14:00:10 73 240 58
删除
Join sense X on X.status = logs.status
当然会输出所有记录,但这不是必需的。
赞赏的想法。
此致
有效
答案 0 :(得分:1)
实际上,您的查询返回5行,每个ID为1行。但它不会为每个id返回带有最新ts的行。您可以通过单击演示链接来验证这一点。您可以比较两个查询的结果。
要完成此任务,以下查询将帮助您:
Select l.assetid, l.ts, logs.nodeid, X.status, X.value
From
logs
inner Join sense X on X.status = logs.status
inner join (select assetid, max(ts) as ts from logs group by assetid) l
on l.assetid = logs.assetid and logs.ts = l.ts
Group by l.assetid
Order by l.ts DESC;
修改强>
如果ts
的dataype是字符串,则将以上查询中的max(ts)
替换为:
max(str_to_date(ts,'%d%m%y'))
随意提出任何疑问。
希望它有所帮助!
答案 1 :(得分:0)
使用GROUP BY
查找每个委托的最低要求,然后使用JOIN
和logs
找出sense
Select *
FROM logs l
JOIN sense s ON s.status = l.status
JOIN
(
Select assetid, max(ts) maxts
From logs
Group by assetid
) t ON t.assetid = l.assetid and l.ts = t.maxts
答案 2 :(得分:0)
试试这个
Select a1.assetid, MAX(a1.ts), a1.nodeid, a1.status, X.value
From
logs a1
inner join sense X on X.status = a1.status
Group by assetid, a1.nodeid, a1.status, X.value
Order by ts DESC
答案 3 :(得分:0)
在MY SQL 8.0.2上
WITH CTE as
(
Select A.assetid, A.ts, A.nodeid, A.status, B.value, row_number() over(PARTITION BY A.assetid ORDER BY A.ts DESC) AS rn
from logs as A
inner join sense B ON A.status=B.status
)
SELECT *
FROM CTE
WHERE rn='1';