我想運行一個查詢,將檢索最近30天有數據(不是最後的30天)獲得最後30獨特的日子,有數據
有可能爲同幾行日期(所以不能使用極限30)
我的數據具有以下格式:
date count
2017-05-05 111
2017-05-05 78
2017-04-28 54
2017-01-11 124
有我的方式來添加一個WHERE
子句,以獲得最新的30天的數據?
我想運行一個查詢,將檢索最近30天有數據(不是最後的30天)獲得最後30獨特的日子,有數據
有可能爲同幾行日期(所以不能使用極限30)
我的數據具有以下格式:
date count
2017-05-05 111
2017-05-05 78
2017-04-28 54
2017-01-11 124
有我的方式來添加一個WHERE
子句,以獲得最新的30天的數據?
不知道如果我理解正確,但...
(這是最近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
select * from tablename
where datecolumn in (select TOP 30 max(datecolumn) from tablename group by datecolumn)
OP想要最後30個日期,而不是最近30個日曆天 – philshem
現在這樣看起來如何? –
如果你想所有的行,它具有相同的date
作爲最後一個30,在你的表不同的日期,你可以使用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)
什麼數據庫您使用的?答案可能會根據你的答案而改變。另外,如果您在同一天有多個條目,是否需要當天的所有條目? – ollie
@ollie它是postgres,不適當更新標籤 – RomainD
請編輯問題以表明您想要最近30個獨特的「日期」,而不是最近30個日曆日內的記錄。 – philshem