我想在过去7天内获取每个产品的最后一个时间戳。数据库中有数千条记录。我怎么能用查询来做到这一点。大约有25种不同的产品,每种产品每天有大约50个时间戳。
表:BuildData
'Timestamp' | 'Product' | 'BuildNo'
'2015-10-21 12:12:00', 'AB', '809'
'2015-10-21 13:12:00', 'AB', '44'
'2015-10-21 12:12:00', 'CD', '408'
'2015-10-21 13:12:00', 'CD', '15'
'2015-10-21 12:12:00', 'ABC', '1699'
'2015-10-21 13:12:00', 'ABC', '1051'
'2015-10-21 14:12:00', 'ABC', '66'
'2015-10-21 15:12:00', 'ABC', '120'
'2015-10-21 13:12:00', 'XYZ', '928'
'2015-10-21 13:12:00', 'XYZ', '37'
'2015-10-21 16:12:00', 'XYZ', '137'
答案 0 :(得分:2)
您可以使用DATE()
来隐藏时间戳,从而获取表格中的所有日期。然后将日期和产品列组合在一起,并在时间戳列上运行MAX()
,以获取每个产品的每天的最后时间戳。
SELECT DATE(Timestamp) AS Date, Product, MAX(Timestamp) AS Last_timestamp
FROM Builddata
WHERE BETWEEN DATE_SUB(NOW(),INTERVAL 1 WEEK) and NOW();
GROUP BY Date, Product
答案 1 :(得分:0)
Select
Timestamp,
Product,
BuildNo
from Yourtable
inner join
-- Selecting max data per product per day
(Select max(timestamp) as MaxTimestamp, Product as MaxProduct from yourTBL
-- You only want the data for the last 7 days
where datediff(timestamp,current_timestamp)<7
group by Product, date_add(0,INTERVAL (datediff(0,timestamp)) DAY )MaxTbl
on MaxProduct = Product and MaxTimestamp=Timestamp