grouping records with all the possible dates - mysql

I need to get the number of records created in a specific period of time. What I'm trying to use right now looks kinda like this:
User.where('created_at between ? and ?', start, finish).group("date(created_at)").count
What i get is hash with dates as keys and numbers as values. BUT when a value is 0 for a specific day, it is not included in the hash. how can i include these dates as well? I mean MySQL, NOT Ruby language, i want it to be as fast as possible.

AR or MySQL can not create the group if there are no records in DB within the given range.
I had a similar issue and I only was able to solve it with Ruby..
User
.where('created_at between ? and ?', start, finish)
.group("date(created_at)")
.flat_map{ |a,b| [a => b.count] }
.inject(:merge)

Related

Query Builder, where compare date shifted by N days

In my laravel app I have a table with 2 relevant fields:
updated_at timestamp of last review
n number of days until next review.
I am trying to write a query that returns records which are due for review. In PHP, I would do something like this:
updated_at->addDays(n) > Carbon::now()
Looking at the query builder docs, I am thinking something like the subquery where clause would be helpful, but am unsure how to approach it. Particularly as I need to use a field from the table in both sides of the where.
->where('updated_at', '>', function ($query) {
//
})

How to separate data of the same time(hour) in ruby on rails?

I have a step table that contains values ​​obtained over the course of a day. I used this to group several values ​​from the same day:
MonitorRecord.where(user_id: id).group_by { |item| item.registered_at.to_date }
I did this to calculate the total number of steps for migrating data from multiple users. It's working fine and the answer is a very easy hash to work with.
Result Hash
I need to do the same for a heart rate table, only this time, separating by hour and no longer by day. I need this separate data to calculate an hourly average.
Is it possible to make a request as in the previous example, but now separating the data by time (hour)?
The registered_at field has the following format: 2019-05-31 18:10:57
I need to access all the data and not group it into a single one.
Any help is appreciated.
You can use this as this will return the data separated by hour and then you can do whatever calculation you need. As this will return you a hash like this {"hour": [rows]}
MonitorRecord.where(user_id: id).group_by { |item| item.registered_at.strftime(%H) }
You use strftime
registerd_at.strftime(%H:%M:%S) // 2019-05-31 18:10:57 => 18:10:57

Select last row from a MySQL query

I have a query that returns some dates which are not in any order. I need to select the last row from the sub query. The problem is all the solutions I can find online uses something like
ORDER BY qry_doc_dates.arrival_date DESC LIMIT 1
Select qry_doc_dates.arrival_date
FROM (qry_doc_date) AS qry_doc_dates
ORDER BY qry_doc_dates.arrival_date DESC
LIMIT 1
which will not serve my purpose because it first orders the dates as DESC(or ASC).
Suppose the qry_doc_date returns :
"2019-05-27",
"2019-05-13",
"2019-05-20",
"2019-05-22",
"2019-07-12",
"2019-05-22",
"2019-07-16",
"2019-05-22"
As we can see that the returned values are not in order. If I use
ORDER BY qry_doc_dates.arrival_date DESC LIMIT 1
then it returns "2019-07-16" But I need "2019-05-22" which is the last row.
EDIT 1:
I am trying to convert this VBA query to MYSQL.
DLast("arrival_date", "qry_doc_date", "[package_id] = " & Me!lstPackage)
I suppose I misunderstood what the VBA query wants to return. Another issue is I do not have means to run this VBA query and check the result myself.
Your question doesn't make too much sense according to the SQL standard. In the absense of an ORDER BY clause the database engine is free to return the rows in any order. This order may even change over time.
So essentially you are requesting the "last random row" the query returns. If this is the case, why don't you get the "first random row"? It doesn't make any difference, does it?
The only way of getting the last random row is to get them all and discard all of them except for the last one.
Now, if you just need one random row, I would suggest you just get the first random row, and problem solved.
In response to the additional information from your edit:
EDIT 1: I am trying to convert this VBA query to MYSQL.
DLast("arrival_date", "qry_doc_date", "[package_id] = " & Me!lstPackage)
I suppose I misunderstood what the VBA query wants to return. Another
issue is I do not have means to run this VBA query and check the
result myself.
Unless your dataset qry_doc_date is ordered by means of an order by clause, the DFirst or DLast domain aggregate functions will return essentially a random record.
This is stated in the MS Access Documentation for these two functions:
You can use the DFirst and DLast functions to return a random record from a particular field in a table or query when you simply need any value from that field.
[ ... ]
If you want to return the first or last record in a set of records (a domain), you should create a query sorted as either ascending or descending and set the TopValues property to 1. For more information, see the TopValues property topic. From a Visual Basic for Applications (VBA) module, you can also create an ADO Recordset object and use the MoveFirst or MoveLast method to return the first or last record in a set of records.
What you need is to in qry_doc_date to include a sequential row number.
Then you can use something like this:
ORDER BY qry_doc_dates.row_number DESC LIMIT 1

Mysql select part of field and return full value

Good day all,
I have a field called mCodes which has the exact length (7) throughout the table but with different values i.e. a few records with 5036100, 5036102, 5036103, 7010100, 7010101 etc.
I am using a select statement to first search for the first 4 characters i.e 5036 which will return all the records with 5036 just fine
I now need to return the actual full value of the records 5036100 etc. without recreating another sql statement. My statement I am using is as follow -
SELECT LEFT(MCODE, 4), MAKE, MODEL, NEWPRICE23 FROM mautogd1015 WHERE LEFT(MCODE, 4) = '5036'
I have racked my brain over this for a few hours now, any help will be appreciated.
Try something like this.
SELECT MCODE, MAKE, MODEL, NEWPRICE23 FROM mautogd1015 WHERE LEFT(MCODE, 4) = '5036'

Exporting Data with a Specific Date

Scenario:
I have a single table in access 2007 with few columns and several thousand records which I have imported form a CSV file via a “DoCmd” statement.
What I want:
I want to export these records but on a basis of specific field content and with another column’s date basis. i.e. I want to export the records with the “EQ” ( content of a columns field “SERIES”) and with a date which is one amongst the many dates the column have.
The “SERIES”, I have defined in “Criteria” in my query and it is working fine as the “SERIES” remains the same every day.
Issues:
The problem is with the date that changes every month and I cannot define or hard-code it in anywhere.
Query is working fine with the file where there is no date, but with a date, it is an issue.
Question:
Can we put a user define textbox, where user can define the date and that date will be taken by the query and will return the records with that defined date? In addition, “SERIES” is already defined in query so the result will be exact.
I use the following statement for exporting the data:
DoCmd.TransferText acExportDelim, "NewFnoSpec", "fnoquery",
"C:\Users\welcome\Desktop\Output.txt", True
Using the following 'WHERE' clause as a starting point to select records for one specific date:
WHERE (((Table1.SERIES)="First") AND ((Table1.MyDate)=#4/4/2014#));
You can prompt the user to enter a date by using:
WHERE (((Table1.SERIES)="First") AND ((Table1.MyDate)=[Enter Date]));
If there was some pattern or rule as to the desired date (i.e. first day of prior month, first Monday of prior month, etc.) you could structure the 'WHERE' clause to handle that without a prompt.
Thank you for your reply and an answer. Your answer is quite helpful. I have tried a little easier way and it worked for me. I put a text box named txtexpdate, on the form and in the query ( design mode ), in criteria I have put this :
Like "" & [Forms]![Futures]![txtexpdate] & ""
This is working fine at this juncture. And thank you once again for your efforts to answer my question. Hope this also will help others as an option to this problem.
Regards
Achal