I am trying to write a query to compare the number of average connections today for a given computer to the number of average connections between 7 and 14 days ago. I figured this was best handled by a window function but I am not able to get the syntax correct for the date.
Assume I have a table of IP addresses and connection records called iptable with soucreip, destinationip, timestamp as the columns. Here is the query I am trying for the previous 7 day window to just get the count per sourceip:
select
sourceip,
destinationip,
timestamp,
count(*) OVER (PARTITION BY sourceip order by timestamp
RANGE BETWEEN now() - '7 day'::Interval PRECEDING
now() - '14 day'::Interval FOLLOWING)
from
iptable;
What is the best way to write this type of query does the window function approach make sense or is there a more optimized way to do things for the case of large tables?
Part of your issue is that you’ve chosen a terrible column name,
"timestamp".timestampis the name of a built-in data type, so to use it as a column name you must"double quote"it everywhere.That’s not all, though. Your window function syntax is wrong. See window function syntax. You forgot the
AND; it’sRANGE BETWEEN .. PRECEDING AND ... FOLLOWING.Also, though it isn’t the cause of the issues, you should use the SQL-standard
current_timestampinstead ofnow().That’ll get you to a new error:
which suggests that the current window function implementation won’t do what you want it to do. Sadly.
Instead I’d just use a plain
GROUP BYwith aWHEREfilter on the input rows.