我正在尝试运行查询,检索最近30天有数据的查询(不是过去30天)
同一日期可能有多行(因此无法使用限制30)
我的数据格式如下:
date count
2017-05-05 111
2017-05-05 78
2017-04-28 54
2017-01-11 124
我有没有办法添加WHERE
条款以获取最近30天的数据?
答案 0 :(得分:-1)
不确定我是否正确理解,但是......
(这是最近2天):
with t(date, count) as(
select '2017-05-05', 111 union all
select '2017-05-05', 78 union all
select '2017-04-28', 54 union all
select '2017-01-11', 124
)
select date from t group by date order by date desc limit 2
答案 1 :(得分:-1)
select * from tablename
where datecolumn in (select TOP 30 max(datecolumn) from tablename group by datecolumn)
答案 2 :(得分:-1)
如果您希望表中包含与最后30个相同date
的所有行,则可以使用dense_rank()
window function:
select (t).*
from (select t, dense_rank() over (order by date desc)
from t) s
where dense_rank <= 30
或IN
,带有子选择:
select *
from t
where date in (select distinct date
from t
order by date desc
limit 30)