Following the answer from Philip Rego, you can use SELECT GETDATE() - 1 to subtract days from a date.
You cannot subtract a timestamp from a timestamp. If a date/time value is the operand of an addition, the other operand must be a duration. Subtracting two date/time values is different from subtracting a duration from a date/time value. The DAYS function calculates the number of days between one date and another.
If you are using tSQL then you could use the DATEDIFF function. You can use this function with hours but if you want fractions of hours then you can use minutes and then convert back to hours. Since it is a calculated field, I would just create a view with the DATEDIFF function for the calculated field.
Definition and UsageThe DATEDIFF() function returns the difference between two dates.
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated: PostgreSQL also supports some interesting shortcuts:
SELECT
'yesterday'::TIMESTAMP,
'tomorrow'::TIMESTAMP,
'allballs'::TIME AS aka_midnight;
You can do the following then:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Date/Time Functions and Operators
datatype-datetime (Especial values).
You can cast a TIMESTAMP
to a DATE
, which allows you to subtract an INTEGER
from it.
For instance, to get yesterday:
now()::DATE - 1
So your query will become:
SELECT org_id, date_at::DATE - 1 AS dateat, COUNT(accounts) AS count
FROM sourcetable
WHERE date_at <= NOW()::DATE - 130
GROUP BY 1, 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With