Hi guys i have a search query that should display all the results between a set date range
the query :
public List<Appointment> appointmentRangeSearch(Date startdatetime, Date endDate) {
Query q = em.createQuery("SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN : date1 AND : date2 ");
q.setParameter("date1", startdatetime, TemporalType.TIMESTAMP);
q.setParameter("date2", endDate, TemporalType.TIMESTAMP);
return q.getResultList();
}
it is returning the errror :
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing [SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN : date1 AND : date2 ].
[34, 77] The expression is not a valid conditional expression.
the data in the table is stored :
2013-12-15 00:00:00.0
how can i complete this search ?
thanks guys
Remove the space between : and date1 from : date1. So your query should be like this:
SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2
Your syntax error has been solved but you might have a logic problem not related to your question. If your datatype is datetime, and the data includes a time portion, then this:
where myField between '2013-12-01' and '2013-12-05'
will not pick up records with values like 2013-12-05 01:00
The solution is to do this
where myField >= '2013-12-01'
and myField < '2013-12-06' -- note that this is one day later
Related
This question already has answers here:
Booking Calendar Arrive & Depart Dates
(2 answers)
Closed 4 years ago.
Hi guys i'm creating a simple web application in Java in which i should book a room. Now my problem concerns the possibility of booking a room in the same period.
Let me explain better, I have 2 types of rooms, bedroom1 and bedroom2. If user1 has booked room1 on 22/08/2018, user2 can not book room1 on the same date.
Since I use a database I thought I could solve it by query.
In particular my database:
Table Name: reservation
id_book,login,email,typeroom,numroom,arrivaldate,departuredate.
I have tried to use this query:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE ( res1.typeroom = res2.typeroom ) AND (res1.arrivaldate = res2.arrivaldate )
But I don't resolve the problem.
Can you help me??
UPDATE.
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
String check = ("SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate\n" +
"FROM reservation res1, reservation res2\n" +
"WHERE res1.numroom = res2.numroom\n" +
"AND ((res1.arrivaldate <= res2.departuredate AND res1.departuredate >= res2.arrivaldate)\n" +
" OR (res2.arrivaldate <= res1.departuredate AND res2.departuredate >= res1.arrivaldate))");
ResultSet rs2 = stmt.executeQuery(check);
int rs = st.executeUpdate("insert into reservation (login,email,typeroom,numroom,arrivaldate,departuredate)values ('"+login+"','"+email+"','"+typeroom+"','"+numroom+"','"+arrivaldate+"','"+departuredate+"')");
I'm trying first to use the database version of your answer. I have write this, to check if the booking is ok or not i should insert an if controller?
I think you mean overlap of reservations for the same room:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE res1.room_no = res2.room_no
AND res1.id_prenotazione != res2.id_prenotazione
AND res1.arrivaldate <= res2.departuredate AND res1.departuredata >= res2.arrivaldate
What should maybe checked too is: you used date equality. If that failed, maybe your table columns are not DATE but DATETIME/TIMESTAMP. That would be understandable
as someone might leave his room at 9:00 and the next enter at say 12:00.
AND (res1.arrivaldate = res2.arrivaldate ) would be wrong. You need a range
e.g AND (res1.arrivaldate > res2.arrivaldate ) AND (res1.arrivaldate < res2.departuredate) or something similar
If you want overlapping periods:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE ( res1.typeroom = res2.typeroom )
AND res1.id_book != res2.id_book
AND (res1.arrivaldate <= res2.departuredate)
AND (res2.arrivaldate <= res1.departuredate)
Describe:
I have a table with timestamp column and i want to get the number of values where the timestamp in specific time window.
My code is as shown in here:
String startTime = "2018-08-08 00:00:00";
String endTime = "2018-08-08 23:59:59";
productDF.where("CREATETIME >= '" + startTime + "' AND CREATETIME <= '" + endTime + "'").count();
I also tried between...and...sentence; and also:
productDF.where(unix_timestamp(col("CREATETIME"), "yyyy-mm-dd hh:mm:ss")
.cast("timestamp")
.between(
Timestamp.valueOf(startTime),
Timestamp.valueOf(endTime)
)).count();
The result i get is 6843.
But when i operate the sql sentence using Navicat:
SELECT COUNT(*) FROM my_table
WHERE CREATETIME BETWEEN '2018-08-08 00:00:00' and '2018-08-08 23:59:59';
it shows 7689.
Problem:
I want to know why i get the different results in Spark and Mysql.....what am i missing here??
Problem solved!
The problem happened because of the TIMEZONE.
In spark env., it get the timezone from_unixtime..So need to set the config.
.config("spark.sql.session.timeZone", "UTC")
But I still don't understand why the spark sql session flow the system timezone instead of just select from the column.....
I need help converting some sql to hibernate sql.
SQL:
String sql = "select time, hour(time) as hour, minute(time) as minute "
+ "from db where time >= DATE_ADD(now(), INTERVAL -24 HOUR) "
+ "group by 2 order by time LIMIT 500";
I use SQLQuery to add scalars. I tried this for HQL:
String hql = "select time, hour(time), minute(time) from db as O "
+ "where O.time >= :time group by 2 order by O.time";
Query query = session.createQuery(hql);
query.setDate("time", calend.getTime()); //calend is a Calendar object
However, this doesn't work. Error says it's an hql error.
Instead of using setDate try using setParameter.
From this link about HQL dates:
"setDate" will truncate the HQL date value and ignore the hours, minutes, seconds.
Using setParameter will interpret the values as the parameter that you indicated by :variable.
My task is to get the records between 2fromdate and todate(given as a input parameters).
i am not able to use between operator for 2 input parameters...
My query as follows...
DELIMITER $$
CREATE DEFINER=`testrunner`#`%` PROCEDURE `usp_GetAllTranasactions`(pFromDate nvarchar(30),pToDate nvarchar(30),pstatus int)
BEGIN
select
ST.UserID,U.Username,
ST.SubscriptionID,
ST.DateOfSubscription,
SM.SubType,
SM.Details,
ST.Amount,
ST.EndDate,
ST.Status
from tr_t_subscriptiontransactions ST
Join tr_m_users U on U.UserID=ST.UserID
join tr_m_subscription SM on SM.SubscriptionID=ST.SubscriptionID
where **ST.DateOfSubscription between (pFromDate and pToDate) and ST.EndDate
between(pFromDate and pToDate) and ST.Status=pstatus;**
END if;
END
here i don't know how to use between parameters..plz help me..i want to retrive record between fromdate and todate..hope u understand..
Let us assume you want all transactions for the month of June 2014
In your user interface the parameter values are:
from_date = 2014-06-01
to_date = 2014-06-30
But you will evaluate against a transaction date & time. How do you ensure that absolutely every transactions on June 30 - right up to midnight - is included in the results?
Here is how: use 2014-07-01 instead of 2014-06-30, and here is what the query would look like - which does NOT use between!
SELECT
ST.UserID
, U.Username
, ST.SubscriptionID
, ST.DateOfSubscription
, SM.SubType
, SM.Details
, ST.Amount
, ST.EndDate
, ST.Status
FROM tr_t_subscriptiontransactions ST
JOIN tr_m_users U
ON U.UserID = ST.UserID
JOIN tr_m_subscription SM
ON SM.SubscriptionID = ST.SubscriptionID
WHERE (ST.DateOfSubscription >= pFromDate AND ST.DateOfSubscription < pToDate + 1)
AND (ST.EndDate >= pFromDate AND ST.EndDate < pToDate + 1)
AND ST.Status = pstatus
;
AVOID between for date ranges because it INCLUDES both the lower and upper boundary values.
... equivalent to the expression (min <= expr AND expr <= max)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
What this can lead to is an "anti-pattern" which look like this:
where dt_field between '2014-06-01 00:00:00' and '2014-06-30 23:59:59'
but there are time units smaller than one second, so that approach is imperfect. Don't attempt to overcome the deficiencies of between by adjusting the upper value this way. The simple and more accurate approach is to use >= and < adjusting the upper value by one whole time unit (usually the next day).
I have a basic SQL Table ( pKey INT, TransDate smallDateTime, Amount Float)
I simply want to emulate this SQL in LINQ
SELECT SUM(Amount) AS result
FROM dbo.Basic
WHERE TransDate >= #startDate
AND TransDate <= #EndDate
I have created the LINQ dbml for this and I can get basic query results for a date range
However I can't find the right syntax to get the SUM over a dateRange, I've tried several variations on the following but either they dont compile, or the result they give cannot be converted to a double
BasicDataContext dContext = new BasicDataContext();
var lnq = from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select new { total = c.Sum(Amount) };
double result = (double)lnq.total;
This should work:
double result = (from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select c.Amount).Sum();