我正在尝试加入2个表并仅选择最新的时间戳和与该最新时间戳关联的字段值
数据表:
DEVICE_COUNT
id device_name platform version timestamp
1 abc 123 x 2013-12-30
2 abc 123 y 2014-01-01
3 def 345 x 2013-12-30
device_list
id device_name Network Division Market
2657 def a f d
2656 abc a b c
期望的结果应该是
device_name platform version network division market timestamp
abc 123 y a b c 2014-01-01
def 345 x a f d 2013-12-30
我使用了以下查询,但我没有得到正确的结果
SELECT
device_count.device_name,
device_count.platform,
device_count.version,
Max(device_count.`timestamp`),
device_list.Network,
device_list.Division,
device_list.Market
FROM
device_count
INNER JOIN device_list ON device_count.device_name = device_list.Device_Name
GROUP BY
device_count.device_name,
device_count.platform,
device_count.version,
device_list.Network,
device_list.Division,
device_list.Market
导致
device_name platform version network division market timestamp
abc 123 x a b c 2013-12-30
abc 123 y a b c 2014-01-01
def 345 x a f d 2013-12-30
不应包括第一条记录。我只想要最新时间戳(记录ID 2)
的版本和平台值答案 0 :(得分:0)
尝试子查询:
SELECT
device_count.device_name,
device_count.platform,
device_count.version,
Max(device_count.`timestamp`),
device_list.Network,
device_list.Division,
device_list.Market
FROM
device_count DC
INNER JOIN device_list ON device_count.device_name = device_list.Device_Name
inner join
(select device_name, max(timestamp) timestamp
from device_count
group by device_name) as DC on DC.timestamp = device_count.timestamp and DC.device_name=device_count.device_name
答案 1 :(得分:0)
一种方法是匹配子选择:
SELECT
device_count.device_name,
device_count.platform,
device_count.version,
device_count.`timestamp`,
device_list.Network,
device_list.Division,
device_list.Market
FROM
device_count
INNER JOIN
device_list
ON device_count.device_name = device_list.Device_Name
WHERE device_count.`timestamp` = (
SELECT MAX(dc2.`timestamp`)
FROM
device_count AS dc2
WHERE
dc2.device_name = device_count.device_name
)