MySQL retrieving rows beween two dates from a DATETIME field - zend-framework2

I am a newbie to Zend Framework 2 and now I'm facing an issue with MySQL’s DATE(). I am unable to retrieve records between two dates in Zend Framework.
SQL query:
SELECT * FROM `tasks` WHERE `assignee` = 1 AND date(`start_date`) BETWEEN "2017-03-01" AND "2017-05-25"
What I’ve tried in ZF2:
public function getTaskCheck() {
$sqlstatement = $this->taskTable->getSql()->select();
$sqlstatement->columns(['*']);
$sqlstatement->where('tasks.assignee=1');
$sqlstatement->where->between('DATE(start_date)', '2017-03-01', '2017-05-25');
return $this->taskTable->selectWith($sqlstatement)->toArray();
}
But this is showing error as unknown field DATE(start_date). In the database start_date field is stored as DATETIME. Any help would be appreciated.

Related

Rails, Count of Users Grouped by created_at day - PostgreSQL

I am using Rails 5, PostgreSQL. I need to get count of users grouped by created_at day, using postgres DATE_TRUNC.
The conditions are users created within a date range and have orders within the same date range.
Below is my code which result in an AmbiguousFunction error
Spree::User.joins(:orders)
.where(spree_orders: { completed_at: params[:start_date]..params[:end_date] })
.order("DATE_TRUNC('day', 'created_at')")
.group("DATE_TRUNC('day', 'created_at')")
.count
The params of start_date and end_date are as follow:
params[:end_date] = Time.current.end_of_day
params[:start_date] = (Time.current - 200.days).beginning_of_day
I get the following error
ActiveRecord::StatementInvalid: PG::AmbiguousFunction: ERROR: function date_trunc(unknown, unknown) is not unique
and even when I explicitly write spree_users.created_at I get the same error.
Is there a better way to achieve the required or a solution for this error?
ActiveRecord::StatementInvalid: PG::AmbiguousFunction
This error occurs when our query contains a column name, which may belong to more than one table. For example, we have two tables, User and Company, and both of them have a column called name. Now the following query would raise an error similar to the one that you are facing:
User.joins(:companies).where("name = ABC")
This happens because we do not specify which table to search the name in. Hence, ActiveRecord gets confused and cannot create a unique query.
In the case mentioned above, the error can be resolved simply by prepending spree_users to the created_at column name used in the order and group queries:
Spree::User.joins(:orders)
.where(spree_orders: { completed_at: params[:start_date]..params[:end_date] })
.order("DATE_TRUNC('day', 'spree_users.created_at')")
.group("DATE_TRUNC('day', 'spree_users.created_at')")
.count
I think you can use date function from sql to get date of timestamp field, and since table User and SpreeOrder has created_at field, you should inform table name (spree_orders.created_at)
Spree::User.joins(:orders)
.where(spree_orders: { completed_at: params[:start_date]..params[:end_date]})
.order("date(spree_orders.created_at)")
.group("date(spree_orders.created_at)")
.count

Wonderware Historian: query the Runtime.Events view

I'd like to query the Runtime.Events view with SQL. I have tried the followings:
select * from Runtime.dbo.Events gives the following error:
OLE DB provider "INSQL" for linked server "INSQL" returned message "Event History no longer supports queries that do not provide time".
select * from Runtime.dbo.Events where EventTime >= '2018-09-01 00:00:00' and EventTime <= '2018-11-01 00:00:00' gives this not descriptive error:
Cannot execute the query "..." against OLE DB provider "INSQL" for linked server "INSQL".
The date format seems to be right, because when I have tried with different format I got error referring to wrong date format.
How to query this view?
Perhaps you're trying to query for these events:
SELECT TOP 1000 *
FROM [A2ALMDB].[dbo].[v_EventHistory]
or these events:
SELECT * FROM Runtime.dbo.EventHistory
WHERE DateTime >= '2018-10-11'
I'm unable to clarify this by a comment due to lack of reputation, so let me post an answer. May be your alarms and events are in A2ALMDB database. If that is the case, try the following query.
SELECT * FROM [A2ALMDB].[dbo].Events WHERE [EventStamp] between '2018-09-01 00:00:00' AND '2018-11-01 00:00:00'

Trying to select distinct list of months from date where year = xxxx - linq to entities

I'm attempting to select a distinct listing of months from a date field where the year = xxxx. I've read other questions and answers on this site but can't seem to get mine working. I'm using the entity framework and linq to entities - here is my latest code:
Function BellMonthlySummaryMonthFiltering(years As Nullable(Of Integer), monthval As Nullable(Of Integer)) As JsonResult
If Not years Is Nothing Then
Dim listMonths As List(Of DateTime) = db.MobileBill_Summary.Where(Function(o) o.InvoiceDate.Year.Equals(years)).Select(Function(s) s.InvoiceDate.Month).Distinct.AsEnumerable.Select(Function(t) New DateTime(1999, t, 1)).ToList
End If
'Return Json(months, JsonRequestBehavior.AllowGet)
End Function
This is the error i get:
Additional information: Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context. I followed the instructions in this article:
Linq to entities distinct year from datetime column
Change your where clause to this:
Where(Function(o) o.InvoiceDate.Year = years)
This is due to how EF does its conversion to SQL.

Is it possible to convert the complex SQL into rails?

SPEC
I need to pick all rooms that don't have a single day with saleable = FALSE in the requested time period(07-09 ~ 07-19):
I have a table room with 1 row per room.
I have a table room_skus with one row per room and day (complete set for the relevant time range).
The column saleable is boolean NOT NULL and date is defined date NOT NULL
SELECT id
FROM room r
WHERE NOT EXISTS (
SELECT 1
FROM room_skus
WHERE date BETWEEN '2016-07-09' AND '2016-07-19'
AND room_id = r.id
AND NOT saleable
GROUP BY 1
);
The above SQL query is working, but I wonder how could I translate it into Rails ORM.
Let's say you have array of room_ids called room_ids:
needed_room_ids = room_ids - RoomSku.where(room_id: room_ids, date: '2016-07-09'..'2016-07-19', sealable: false).pluck(:room_id)
If your model of room_sku is called RoomSku
Updated version:
room_ids = Room.all.select { |record| record.room_skus.present? }.map(&:id)
And then:
needed_room_ids = room_ids - RoomSku.where(room_id: room_ids, date: '2016-07-09'..'2016-07-19', sealable: false).pluck(:room_id)
It won't be one query, but you avoid plain SQL like this.
I don't have any project here to test something like it, but it should work:
Room.where.not(id: RoomSku.where(date: DateTime.parse('2016-07-09').strftime("%Y-%m-%d")..DateTime.parse('2016-07-19').strftime("%Y-%m-%d"), saleable: false).pluck(:room_id))
I hope it helps!

I have Two Dates 'Begin Date' and ' End Date' in asp.net MVC, I want to run a loop start from 'Begin Date' to 'End Date'

I want to run a loop in Asp.net MVC using two dates and want to fetch all data from database that exist between these two dates, Please help me.
If you need to make it via Razor, then you can use such code:
#for (DateTime item = model.BeginDate; item <= model.EndDate; item = item.AddDays(1))
{
<div>Date is #item</div>
}
But if you need to fetch data from DB, it will be better to include it in the SQL query that fetch this data with BETWEEN keyword. Here is a sample:
SELECT * FROM SomeSource WHERE DateColumn BETWEEN #BeginDate AND #endDate
UPDATE1
I didn't use nHibernate before, but seems there is an answer on SO about it - Querying with nHibernate where todays date is between publishDate and Expiry date
Basically you can write such code:
DateTime beginDate, endDate;
// init datetime values
return _session.CreateCriteria<Message>()
.Add(
Restrictions.Le("BeginDate", beginDate)
& Restrictions.Ge("EndDate", endDate))
.List<SomeResultType>();

Resources