informix sql where get data less 60 days old from today - informix

I need help writing where clause that will restrict my data to only retrieve past 60 days.
select
name
date
from ....
where date is 60 days older from today.
Require this in informix sql.

This will obviously need adapted to your environment...
SELECT name, date from table WHERE date >= TODAY - 60

Related

Rails query data by hour

I'm having difficulty querying data by an hour for the previous day. Using Rails 4 on Postgres.
eg,
Table X:
created_at, value
timestamp1 3
timestamp2 5
I want to get:
time, value
YYMMDD 00:00 15
YYMMDD 01:00 20
basically the sum per hour. I've tried
Rails & Postgresql: how to group queries by hour?
Is it possible to group by hour/minute/quarter hour directly in ActiveRecord/Rails?
but I still cant figure out how to get it to work properly, i get the wrong hour for replies. How would i set my timezone along with this query?
TableX.group("DATE_trunc('hour',created_at)").count
Thanks!
All you need is create a query like this one:
SELECT date_trunc('hours', created_at), sum(value)
FROM TableX
GROUP BY date_trunc('hours', created_at)
This one uses date_trunc instead of suggested date_part, which fits your question better.

SQLite on iOS date functions using system timezone even though default timezone for the app has been set

I'm working on an app in which users can log in and select a site which may be in a different time zone. Because the app is showing data that is relevant to that site I've decided to set the default timezone for the app to be the site timezone via NSTimeZone.setDefaultTimeZone. This works great except when I select data out of our sqlite db via FMDB (I don't think FMDB has anything to do with it) and use strftime with 'localtime'. While our data is stored by the minute in UTC using epochs, we often need to show summations by day, weekday or month in the local time zone. For example to get averages by weekday:
select strftime('%w',datetime(epoch,'localtime')),avg(value)
from values
where siteId = 'x'
group by 1
order by 2 desc
The 'localtime' that it's using is the system local time and not the default time zone for the app where all NSDate calls respect the default time zone. There does not to be any other timezone options for strftime other than localtime and UTC and the current work arounds are pretty slow requiring multiple SQL roundtrips where this should easily be handled in 1 query as above.
Can anyone tell me how sqlite on iOS determines 'localtime'? Is there a way to force it to use a different i.e. defaultTimeZone?
As you have seen, SQLite doesn't use NSDate or the app's local timezone. The datetime function converts with a Modifier. Say you had a DB that stores as GMT (I think this is the case for your app):
sqlite> create table mytable (id int, time datetime);
sqlite> insert into mytable values (1, CURRENT_TIMESTAMP);
sqlite> select time from mytable;
2016-06-24 19:05:36 <- THIS IS GMT
sqlite> select datetime(time, 'localtime') from mytable;
2016-06-24 15:05:36 <- THIS IS LOCAL TIME
In this example (and yours) 'localtime' is the Modifier. From the sqlite docs:
Modifiers
The time string can be followed by zero or more modifiers that alter
date and/or time. Each modifier is a transformation that is applied to
the time value to its left. Modifiers are applied from left to right;
order is important. The available modifiers are as follows.
NNN days
NNN hours
NNN minutes
NNN.NNNN seconds
NNN months
NNN years
start of month
start of year
start of day
weekday N
unixepoch
localtime
utc
So you cannot directly convert to the local value. However, because you can use these modifers your app can get your local GMT offset from NSDate:
if let myZone = NSTimeZone(abbreviation: "EST")
{
NSTimeZone.setDefaultTimeZone(myZone)
var offset = (myZone.secondsFromGMT)/3600 as Int
var offsetModifer = "\(offset) hours"
}
Then you can execute your sqlite query as so (building the query using offsetModifer which translates to -4 hours in the example here:
sqlite> select datetime(time, '-4 hours') from mytable;
2016-06-24 15:05:36

Possible to use field in ActiveRecord query?

I have a DateTime in my at field and a number of minutes duration in my minutes field. I want to get all the records where the current time falls within at and at + minutes. Something like:
SpecialEvent.where(at: (DateTime.now - 120.minutes)..DateTime.now)
Except I'm guessing the 120.minutes duration. The exact number of minutes duration for each SpecialEvent is in a minutes field. But I don't know how to use that minutes field within the query...
Some databases (including MySQL) support functions in SQL to perform calculations with dates. This is required to efficiently calculate the timestamp based on data inside the database. Thus, you need to generate correct SQL for your specific database flavour. The example below should work for MySQL. If you use another database, you probably need to adapt this to the available date functions.
SpecialEvent.where(['at >= :now - INTERVAL minutes MINUTE AND at <= :now', now: DateTime.now])
This effectively generates the following SQL query (although with a literal date value instead of NOW():
SELECT * FROM special_events WHERE at >= NOW() - INTERVAL minutes MINUTE AND at <= NOW();
You can format your query like:
SpecialEvent.where(at: (DateTime.now - 120.minutes)..DateTime.now, minutes: '<your search value>')

Find all data that were created between 9 am and 4pm Rails 3.2.1 and postgreSQL

I have a requirement to display all data that were inserted in between 9 am and 5 pm ignoring dates.
I have tried
.where(created_at: Time.parse("9am")..Time.parse("5pm"))
*Because Time.parse results in current data and time. So this display only today's result between 9 am and 5 pm.But I need all the data that were entered in between 9am and 5pm *
I tried to solve using time data field in database. Database stores correctly but when we query through rails the year 01-01-2000 was appended in time.
Although it is a very simple problem, I am stuck.
Please help me to figure out this problem.
PostgreSQL defines a function EXTRACT described here: http://www.postgresql.org/docs/current/interactive/functions-datetime.html
You might be able to query using something like the following:
SELECT * FROM (modelname) WHERE EXTRACT(HOUR FROM created_at) > (minhour) AND EXTRACT(HOUR FROM created_at) < (maxhour);

Rails: find by day of week with timestamp

I need to grab the records for same day of the week for the preceeding X days of the week. There must be a better way to do it than this:
Transaction.find_by_sql "select * from transactions where EXTRACT(DOW from date) = 1 and organisation_id = 4 order by date desc limit 7"
It gets me what I need but is Postgres specific and not very "Rails-y". Date is a timestamp.
Anyone got suggestions?
How many days do you want to go back?
I have written a gem called by_star that has a dynamic finder suited for finding up to a certain number of days in the past. If the number of days was always a number you could use this finder:
Transaction.as_of_3_days_ago
If it was dynamic then I would recommend using something such as future or between, depending on if you have transactions in the future (i.e. time travel):
Transaction.future(params[:start_date].to_time)
Transaction.between(params[:start_date].to_time, Time.now)
AFAIK Rails has no any methods to do this by other way. So best, and faster, solution - build DOW index on date column and use your query.

Resources