mysql - 返回行中的mysql Max(日期)值
问题描述
我查询时在 mytable 中
SELECT * FROM mytable WHERE adsh='0000002178-18-000009' and tag='assets'
我得到这个结果
adsh tag ddate value
0000002178-18-000009 Assets 2016-12-31 246872000.00
0000002178-18-000009 Assets 2017-12-31 282704000.00
但我希望只返回包含 max(ddate) 的行,即 2017-12-31 行注意还有许多其他不同的标签。但是由于该表包含 >100k 行,因此我希望确保在将其扩展到所有行之前进行正确的查询。
我尝试了许多不同的查询和变体,但没有雪茄:/
SELECT *,max(ddate) FROM mytable WHERE adsh='0000002178-18-000009' and tag='Assets'
返回错误的行
SELECT * FROM mytable
WHERE ddate = (select max(ddate) and adsh='0000002178-18-000009' and tag='Assets' from mytable)
返回 0 行
SELECT * FROM mytable
WHERE ddate = (select max(ddate) and adsh='0000002178-18-000009' and tag='Assets' from mytable)
返回 0 行
SELECT DISTINCT adsh,tag,ddate,value from mytable
WHERE ddate = (select max(ddate) from mytable) group by adsh
但这也不是我所期望的
有谁知道我怎么能做到这一点?
太感谢了 :)
解决方案
你似乎想要:
select *
from mytable
where ddate = (
select max(ddate)
from mytable
where adsh='0000002178-18-000009' and tag='Assets'
)
where
通过重复外部查询子句中的条件,您将获得更准确的信息:
select *
from mytable
where adsh = '0000002178-18-000009' and tag = 'Assets' and ddate = (
select max(ddate)
from mytable
where adsh = '0000002178-18-000009' and tag = 'Assets'
)
以防万一,让我指出,如果您确定没有顶级关系,这可以更简单地完成limit
:
select *
from mytable
where adsh = '0000002178-18-000009' and tag = 'Assets'
order by dddate desc limit 1
最后:如果你运行的是 MySQL 8.0,你也可以使用窗口函数:
select *
from (
select t.*,
rank() over(order by ddate desc) as rn
from mytable t
where adsh = '0000002178-18-000009' and tag = 'Assets'
) t
where rn = 1
推荐阅读
- python - Glade 检测到错误的 Gtk+ 版本
- javascript - 在空输入旁边添加 *Required
- c++ - 如何使用位域将数据从二进制文件复制到结构中?
- reactjs - 你如何使用 jest 和 react-testing-library 测试元素的不存在?
- c++ - 变量超出范围后如何保留向量值?
- python - 如何在 tkinter 中创建任意数量的输入框?
- c++ - 尽管在 openCV 4.0.0 中正确寻址,imread() 仍然返回空垫
- google-home - 如何将 Dialogflow 聊天机器人部署/测试到实际的 Google Home 设备?
- python - 根据列值对有序熊猫数据框中的行进行分组
- html - flex 项目未在导航栏中垂直对齐