简体   繁体   English

SQL按日期选择最新行

[英]SQL Select latest row by date

I have a large amount of data that updates every 10 minutes or so. 我有大量的数据每10分钟左右更新一次。

There are 128 unique ID's that need to be returned but with only there latest values 有128个唯一ID需要返回,但只有最新值

CURRENT CODE 当前代码

SELECT DISTINCT 
id, 
MAX(extractdate) AS [extractdate],
total,
used,
free

FROM
maintable
INNER JOIN datatable ON maintable.unkey = datatable.dataunkey

GROUP BY id, total, used, free

ORDER BY id

CURRENT OUTPUT 电流输出

id      extractdate                 total   used    free
1       2014-08-28 00:20:00.000     50      20      30
1       2014-08-28 00:30:00.000     50      30      20
1       2014-08-28 00:40:00.000     50      10      40
2       2014-08-28 00:20:00.000     50      20      30
2       2014-08-28 00:30:00.000     50      30      20
2       2014-08-28 00:40:00.000     50      25      25
etc etc

**DESIRED OUTPUT**

id      extractdate                 total   used    free
1       2014-08-28 00:40:00.000     50      10      40
2       2014-08-28 00:40:00.000     50      25      25
etc etc

Should work, i've just tested it on the similar fall, only without join: 应该可以,我刚刚在类似的秋天测试过它,只是没有加入:

SELECT id, extractdate,total,used,free
FROM maintable m INNER JOIN datatable ON m.unkey = datatable.dataunkey
where extractdate = (select max(extractdate) from manitable m1 where m1.id = m.id) 
ORDER BY id

Try: 尝试:

SELECT 
a.id,
a.extractdate,
a.total,
a.used,
a.free
FROM(
SELECT  
id, 
MAX(extractdate) AS [extractdate],
total,
used,
free,
ROW_NUMBER()OVER(partition by id ORDER BY MAX(extractdate) desc) AS rnk
FROM maintable
INNER JOIN datatable ON maintable.unkey = datatable.dataunkey
GROUP BY id, total, used, free )a
WHERE a.rnk = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM