Retrieve database records between two weekdays - laravel

I have several records in my database, the table has a column named "weekday" where I store a weekday like "mon" or "fri". Now from the frontend when a user does search the parameters posted to the server are startday and endDay.
Now I would like to retrieve all records between startDay and endDay. We can assume startDay is "mon" and endDay is "sun". I do not currently know how to do this.

Create another table with the names of the days and their corresponding number. Then you'd just need to join up your current table with the days table by name, and then use the numbers in that table to do your queries.

Not exactly practical, but it is possible to convert sun,mon,tue to numbers using MySQL.
Setup a static year and week number like 201610 for the 10th week of this year, then use a combination of DATE_FORMAT with STR_TO_DATE:
DATE_FORMAT(STR_TO_DATE('201610 mon', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 sun', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 tue', '%X%V %a'), '%w')
These 3 statements will evaluate to 0,1,2 respectively.
The main thing this is doing is converting the %a format (Sun-Sat) to the %w format (0-6)

well i don't know the architecture of your application as i think storing and querying a week day string is not appropriate, but i can tell you a work around this.
make a helper function which return you an array of weekdays in the range i-e
function getWeekDaysArray($startWeekDay, $endWeekDay) {
returns $daysArray['mon','tue','wed'];
}
$daysRangeArray = getWeekDaysArray('mon', 'wed');
now with this array you can query in table
DB::table('TableName')->whereIn('week_day', $daysRangeArray)->get();
Hope this help

Related

Split up date range into chunks to join back into one table KDB+/Q

I have a table that is being joined like so
result: select from table where date within (sd;ed)
where sd and ed span multiple months (like sd:2021.07.01 ed:2021.09.30). The table that I'm querying from has a break if you take more than a month, so to get the result I need, I have to do something like the following:
result: uj(uj(select from table where date within (2021.07.01;2021.07.30);select from table where date within (2021.08.01;2021.08.31));select from table where date within (2021.09.01;2021.09.30))
How can I make this dynamic for any sd and ed? That is, how can I break up time range into first days of months, last days of months, and join them all into one table cleanly? My initial idea was to divide the days in the range x amount of time, to be input by a user, then add the number of days that results to the sd to get frames, but that got messy.
Something like this should chunk it for you:
raze{select from t where date within x}each(first;last)#\:/:d group"m"$d:sd+til 1+ed-sd
Do not use where date.month=x as you had suggested - at least not for historical queries
One option for converting your start and end dates into an iterable list of dates might be:
f:{0N 2#(x,raze -1 0+/:`date$mx+1+til(`month$y)-mx:`month$x),y}
Where x is start date and y is end date.
f[2021.07.14;2022.02.09]
2021.07.14 2021.07.31
2021.08.01 2021.08.31
2021.09.01 2021.09.30
2021.10.01 2021.10.31
2021.11.01 2021.11.30
2021.12.01 2021.12.31
2022.01.01 2022.01.31
2022.02.01 2022.02.09
Then you could run:
{select from t where date within x} each f[sd;ed]
And join the results using raze or (uj/)

ActiveRecord count of distinct days from created_at?

Is it possible to retrieve a count of distinct records based on a field value if the field needs to be interrogated (ideally, using ActiveRecord alone)?
For example, the following returns a count of unique records based on the 'created_at' field:
Record.count('created_at', :distinct => true)
However, is it possible to get a count of, say, unique days based on the 'created_at' field in a similar way?
A naive ActiveRecord example to explain my intent being:
Record.count('created_at'.day, :distinct => true)
(I know the string 'created_at' isn't a 'Time', but that's the sort of query I'd like to ask ActiveRecord.)
You need to group the records. For example
Record.group('DATE(created_at)').count('created_at')
tells you the number of rows created on each particular date, or
Record.group('DAYOFWEEK(created_at)').count('created_at')
would tell you the number of rows created on individual days of the week.
Beware that this with the usual active record setup this will do date calculations in UTC, if you want to do your calculations in a specific timezone you'll have to add that conversion to the group statement.

Play Framework: How to render a table structure from plain SQL table

I would be happy to get a good way to get the "table" structure from a plain SQL table.
In my specific case, I need to render JSON structure used by Google Visualization API "datatable" object:
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable
However, having an example in HTML would help either.
My "source" is a plain SQL table of "DailySales": its columns are "Day" (date), "Product" and "DailySaleTotal" (daily sale for that product). Please recall that my "model" reflects the 3-column table above.
The table columns should be "products" (suppose we have very small number of such). Each row should represent a specific date, and the row data are the actual sales for that day.
Date Product1 Product2 Product3
01/01/2012 30 50 60
01/02/2012 35 3 15
I was trying to use nested #{list} tags in a template, but unfortunately I failed to find a natural way to provide a template with a "list" to represent the "row data".
Of course, I can build a "helper object" in Java that will build a list of the "sales data" items per date - but this looks very weird to me.
I would be thankful to anyone who can provide an elegant solution.
Max
When you load your model order it by date and product name. Then in your controller build a map with date as index and list of model objects that have the same date as value of the map
Then in your template you have a first list iteration on map keys for the rows and a second list iteration on the list value for the columns.
Something like
[
#{list modelMap.keys, as: 'date'}
[${date},#{list modelMap.get(date), as: 'product'}${product.dailySaleTotal}#{ifnot product_isLast},#{/ifnot}#{/list}]#{ifnot date_isLast},#{/ifnot}
#{/list}
]
you can then adapt your json rendering to the exact structure you want to have. Here it is an array of arrays.
Instead of generating the JSON yourself, like Seb suggested, you can generate it:
private static Result queryToJsonResult(String sql) {
SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
return ok(Json.toJson(sqlQuery.findList()));
}

How can I compare 2 dates in a Where statement while using NoRM for MongoDB on C#?

I have a table in Mongo. One of the fields is a DateTime. I would like to be able to get all of the records that are only for a single day (i.e. 9/3/2011).
If I do something like this:
var list = (from c in col
where c.PublishDate == DateTime.Now
select c).ToList();
Then it doesn't work because it is using the time in the comparison. Normally I would just compare the ToShortDateString() but NoRM does not allow me to use this.
Thoughts?
David
The best way to handle this is normally to calculate the start datetime and end datetime for the date in question and then query for values in that range.
var start = DateTime.Now.Date;
var end = start.AddDays(1);
...
But you'd also be well advised to switch to the official C# driver now. You should also use UTC datetimes in your database (but that gets more complicated).

Combining all dates, and data, within a month!

I am trying to combine all days of each month into a date.
My query as off now:
SELECT
inventory_items.acquired_at AS Date_Acquired,
products.name AS products_name,
SUM(inventory_items.primary_quantity) AS inventory_items_primary_quantity
FROM
inventory_items inventory_items INNER JOIN customers customers ON inventory_items.source_id = customers.id
INNER JOIN products products ON inventory_items.product_id = products.id
GROUP BY
MONTH(Date_Acquired),
products_name
ORDER BY
MONTH(Date_Acquired)
I have a general idea of what to do, but not really sure how to implement it.
As I understand you and your Date_Acquired is an instance of sql Date type
you can gat day of months as pasting below code inside a textfield
(new SimpleDateFormat("d")).format(new java.util.Date())
which suppose to give you numbers like 1,2,3,...18,19...
Extra:
(new SimpleDateFormat("M")).format(new java.util.Date()) for month
(new SimpleDateFormat("yyyy")).format(new java.util.Date()) for year
(new SimpleDateFormat("d")).format(new java.util.Date())+" - "
+(new SimpleDateFormat("M")).format(new java.util.Date()) for getting a value like 28 - 01
What database? A typical SQL database result can only contain one data value per field. So you will not be able to retrieve all the products.name values in one result grouped by the month. If you retrieve all the results under a specified month you can aggregate them later on.

Resources