What is the use of such a function? If I saw this answer I would assume a bug somewhere (until reading the documentation).
What is the use of such a function? If I saw this answer I would assume a bug somewhere (until reading the documentation).
GROUP BY DATEDIFF('month', "transaction_date", NOW())
And get a result set that shows the relative month in one column, and the sum in another.And those values relative values won't change every month like they would if I just grouped by
EXTRACT('year-month', "transaction_date")
(or whatever the syntax is for that)Also useful for a stored procedure or view than can then be JOINed in other queries as time goes on.
MonthsAgo | Sales
==================
4 | 4,500
3 | 7,204
2 | 12,578
1 | 15,748
0 | 34,485
And maybe use a parameter so the user can go by week, or quarter, or whatever.For example, find all users who have have been active at least 10 days. This provides a simple way to do a complex operation (if a user signs up Dec 29, a naive implementation won't catch that their 10 days is in January of the next year).
A naive implementation would accidentally get tripped up by the year -- extracting the 'day' part of a timestamp, as an integer, gives you the day from the start of the year. So on one side of the year boundary you have 365 and on the other you have 1. The way to do it correctly is to multiply the day in the year by the year itself so that a '1' on a later year is a bigger number.
And of course grouping by year isn't always what you want to do :)
If you care about Days, you normally absolutely -should- use DATEDIFF('DAY' instead of DATEDIFF('YEAR' and act accordingly. The bigger thing is the semantics they provide.
Frankly, this can be a pain point at times, but IIRC PostgreSQL at least is very work-aroundable, IIRC you can get the equivalent for most common cases off the interval from an add/sub.
Honestly, Dates in SQLite are harder to deal with in the long term, since without a native data type you have to write at least the level of conversions you would in PostgreSQL. (e.x. just convert everything to/from tics at the abstraction layer.)
Edit: Also I would suggest considering instead use of getdate() <= DATEADD('day', signup_date,1) or a variant as that is probably more cross DB friendly
In my experience you almost always want to count intervals for analysis and not interval boundaries. For example when calculating someone’s age in years.
The use cases for interval boundaries seem to mostly be businesses rules based on contract dates.
Well, then you only need to compare the difference of the timestamp (or date) values with an interval of 10 days. e.g. end_time - start_time >= interval '10 days'