[英]Rolling 7 Day Count Distinct in postgresql
我有一個包含2列的表:
日期:從1/1 / 16-12 / 31/16起的所有日期
ID:是文本字段的唯一標識符。 特定ID可能會或可能不會在多天內出現。
我想計算每天滾動7天的不同ID。 這是SQL可以完成一天的工作:
16年1月7日:
Select '2017-01-07' as week_end_date, count(distinct(id)) as ids
from table
where date between '2016-01-01' and '2016-01-07'
而不是對每個日期運行365次以上查詢,是否有任何方法可以在一個查詢中執行此操作?
計數不同的ID是很棘手的。 如果性能不是問題,則可以執行以下操作:
Select week_start_date + interval '6 day' as week_end_date,
count(distinct id) as ids
from table join
generate_series('2016-01-01'::date, '2017-01-01'::date, interval '1 day') as g(week_start_date)
where date between week_start_date and week_start_date + interval '6 day';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.