【问题标题】:mysql Max(date) value in returned rows [duplicate]返回行中的mysql Max(date)值[重复]
【发布时间】:2021-03-25 08:54:57
【问题描述】:

查询时在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 adsh='0000002178-18-000009' AND tag='assets' ORDER BY dddate DESC LIMIT 1

标签: mysql sql datetime max greatest-n-per-group


【解决方案1】:

你似乎想要:

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

【讨论】:

猜你喜欢
  • 2020-03-10
  • 2021-04-25
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
相关资源
最近更新 更多