这是我的SQL:
SELECT * FROM unity_database.unit_uptime_daily
inner join unity_database.units on unity_database.units.id = unity_database.unit_uptime_daily.unit_id
where unity_database.units.location_id = 1
我试图只为每个具有最新日期的unit_id显示一个结果,所以在这个例子中,unit_id为30的单位应该只显示一次,它应该是底行。
有什么想法吗?
答案 0 :(得分:1)
WITH X AS
(
SELECT *
,ROW_NUMBER() OVER (PARTITION BY Unit_Id ORDER BY [Timestamp] DESC) rn
FROM unity_database.unit_uptime_daily
inner join unity_database.units
on unity_database.units.id = unity_database.unit_uptime_daily.unit_id
where unity_database.units.location_id = 1
)
SELECT * FROM X Where rn = 1
OR
SELECT *
FROM (
SELECT *
,ROW_NUMBER() OVER (PARTITION BY Unit_Id ORDER BY [Timestamp] DESC) rn
FROM unity_database.unit_uptime_daily
inner join unity_database.units
on unity_database.units.id = unity_database.unit_uptime_daily.unit_id
where unity_database.units.location_id = 1
)A
WHERE rn = 1
答案 1 :(得分:1)
这是您可以考虑的MySQL解决方案:
SELECT t1.id, t1.unit_id, t1.uptime, t1.total_update, t2.timestamp
FROM
(
SELECT *
FROM unity_database.unit_uptime_daily ud1 INNER JOIN unity_database.units ud2
ON ud2.id = ud1.unit_id
WHERE ud2.location_id = 1
) t1
INNER JOIN
(
SELECT ud1.unit_id, MAX(ud1.timestamp) AS timestamp
FROM unity_database.unit_uptime_daily ud1 INNER JOIN unity_database.units ud2
ON ud2.id = ud1.unit_id
WHERE ud2.location_id = 1
GROUP BY ud1.unit_id
) t2
ON t1.unit_id = t2.unit_id AND t1.timestamp = t2.timestamp
答案 2 :(得分:0)
如果这个答案能够为您提供您期望的结果:
SELECT MAX(id) AS ID, unit_id, uptime, total_update, MAX(timestamp) as timesstamp FROM unity_database.unit_uptime_daily
inner join unity_database.units on unity_database.units.id = unity_database.unit_uptime_daily.unit_id
where unity_database.units.location_id = 1
GROUP BY unit_id, uptime, total_update
PS:我没有测试,但我很肯定它会起作用