select results from one date field compared to another + 24 hours - sql

I need to pull values from one table that are only 24 hours from the date in another table in sybase ase 15.5.
Here is my wrong code:
SELECT p_generaldata.admissiontime,*
FROM Patient.dbo.P_MonVals P_MonVals
INNER JOIN Patient.dbo.P_GeneralData P_GeneralData
ON P_MonVals.PatientID=P_GeneralData.PatientID
where p_generaldata.admissiontime < P_MonVals.entertime +1
order by p_generaldata.patientid ASC
Im trying to return all rows in p_monvals, where the entertime in that table is less than 24 hours after the admissiontime.
the error im getting is INT is not compatible with DATETIME
Any help greatly appreciated
thank you

Take a look a the DateAdd function, and add a day to the entertime
Example from docs:
Adds one day to a date:
declare #a date
select #a = "apr 12, 9999"
select dateadd(dd, 1, #a)
In your case...
...
where p_generaldata.admissiontime < dateadd(dd, 1, P_MonVals.entertime)

Use function dateadd to sum 1 day in your date time:
dateadd(dd, 1, P_MonVals.entertime)
Reference: Sybase dateadd function.

You want to use the dateadd function:
SELECT p_generaldata.admissiontime, *
FROM Patient.dbo.P_MonVals P_MonVals
INNER JOIN Patient.dbo.P_GeneralData P_GeneralData
ON P_MonVals.PatientID=P_GeneralData.PatientID
WHERE p_generaldata.admissiontime < DATEADD(dd, 1, P_MonVals.entertime)
ORDER BY p_generaldata.patientid ASC

Related

How to i find records in the last month that do not have a "Date created" column

Im trying to find records that have not had notes created during the last 1 month. The table only registers when a note is created.
I am trying to find NULL values, but that would not be the correct logic
SELECT *
FROM vpersonnotesalldata AS pn
WHERE pn.flddatecreated > '20190501'
AND pn.fldnotedatecreated < '20190530'
If you want records which don't have a note in last 30 days, try this:
select p.* from person p where personid not in (
select personid from Note where dateCreated < dateadd(d, -30, GetDate())
)
Obviously use your actual table names in your sql
Try this with example last month
SELECT *
FROM vpersonnotesalldata AS pn
WHERE pn.NoteColumnHERE IS NULL
AND pn.CreateDateColumnHERE
BETWEEN '01.05.2019'
AND '31.05.2019'
It picks all pn.NoteColumnHERE which are NULL in the Span of pn.CreateDateColumnHERE BETWEEN 01.05. and 31.05.
I hope the Date Input is correct for your SQL Version. In Microsoft SQL it is working!
The performance will be much better if you use EXISTS / NOT EXISTS instead of IN / NOT IN
SELECT *
FROM Client C
WHERE NOT EXISTS (
SELECT 1
FROM vpersonnotesalldata
WHERE
fldClientNumber = C.fldClientNumber
AND fldnotedatecreated BETWEEN
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month
)

Display a date that is the same as today in SQL Server [duplicate]

I have a table TEST with a DATETIME field, like this:
ID NAME DATE
1 TESTING 2014-03-19 20:05:20.000
What I need a query returning this row and every row with date 03/19/2014, no matter what the time is. I tried using
select * from test where date = '03/19/2014';
But it returns no rows. The only way to make it work that I found is to also provide the time portion of the date:
select * from test where date = '03/19/2014 20:03:02.000';
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the
time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
Simple answer;
select * from test where cast ([date] as date) = '03/19/2014';
I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -
select * from test where DATE(date) = '2014-03-19';
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
This works for me for MS SQL server:
select * from test
where
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
This is a realy bad answer. For two reasons.
1.
What happens with times like 23.59.59.700 etc.
There are times larger than 23:59:59 and the next day.
2.
The behaviour depends on the datatype.
The query behaves differently for datetime/date/datetime2 types.
Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.
select convert (varchar(40),convert(date , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
-- For date the value is 'chopped'.
-- For datetime the value is rounded up to the next date. (Nearest value).
-- For datetime2 the value is precise.
use this
select * from TableName where DateTimeField > date() and DateTimeField < date() + 1
Try this
select * from test where Convert(varchar, date,111)= '03/19/2014'
you can try this
select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';
There is a problem with dates and languages and the way to avoid it is asking for dates with this format YYYYMMDD.
This way below should be the fastest according to the link below. I checked in SQL Server 2012 and I agree with the link.
select * from test where date >= '20141903' AND date < DATEADD(DAY, 1, '20141903');
Bad habits to kick : mis-handling date / range queries
You can use this approach which truncates the time part:
select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)
-- Reverse the date format
-- this false:
select * from test where date = '28/10/2015'
-- this true:
select * from test where date = '2015/10/28'
Simply use this in your WHERE clause.
The "SubmitDate" portion below is the column name, so insert your own.
This will return only the "Year" portion of the results, omitting the mins etc.
Where datepart(year, SubmitDate) = '2017'
select *, cast ([col1] as date) <name of the column> from test where date = 'mm/dd/yyyy'
"col1" is name of the column with date and time
<name of the column> here you can change name as desired
select *
from invoice
where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));
Test this query.
SELECT *,DATE(chat_reg_date) AS is_date,TIME(chat_reg_time) AS is_time FROM chat WHERE chat_inbox_key='$chat_key'
ORDER BY is_date DESC, is_time DESC
select * from invoice where TRANS_DATE_D>= to_date ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date ('20171031115959','YYYYMMDDHH24MISS');
SELECT * FROM test where DATEPART(year,[TIMESTAMP]) = '2018' and DATEPART(day,[TIMESTAMP]) = '16' and DATEPART(month,[TIMESTAMP]) = '11'
use trunc(column).
select * from test t where trunc(t.date) = TO_DATE('2018/06/08', 'YYYY/MM/DD')

SQL statement to get a total for a given date range

I am trying to get the number of bookings and their total value by date for every day within a given date range.
My table looks like:
BookingId (int)
BookingFare (decimal)
BookingDateTime (datetime)
I can convert BookingDateTime to a date only by using:
SELECT CONVERT(varchar(8), BookingDateTime, 112) as BookingDateOnly
FROM [TaxiBookingOnline].[dbo].[Bookings]
What I'm after is something like this:
Date Bookings Value
2013-07-10 10 256.24
2013-07-11 12 321.44
2013-07-12 14 311.53
I get the feeling I should be aliasing the table, joining it to itself and then using 'GROUP BY' but I am failing to get this to work.
Any help would be much appreciated.
Thanks.
How about
select
cast(BookingDateTime as date) [Date],
count(*) [Bookings],
sum(BookingFare) [Value]
from t
group by cast(BookingDateTime as date)
SELECT CONVERT(VARCHAR(8), BookingsDateTime, 112) AS [Date],
COUNT(*) AS [Bookings],
SUM(BookingsFare AS [Value]
FROM MyTable
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, BookingDateTime))
Group by SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, dateColumn)) which will effectively get the date portion of the datetime, then you can use count or sum as necessary on the grouped values.
EDIT: If you're using SQL Server >= 2008, you can cast to date (like #AlexK has done) otherwise you have to hack around it using DATEADD.
Following is the code. Replace Date1 and Date2 with the date range values:
SELECT
CONVERT(varchar(8), BookingDateTime, 112) as BookingDateOnly, BookingID Bookings,Sum(BookingFare)Value
FROM
[TaxiBookingOnline].[dbo].[Bookings]
WHERE BookingDateTime Between 'Date1' and 'Date2'
GROUP BY
BookingDateTime,BookingID
SELECT
CONVERT(DATE,BookingDateTime) BookingDate,
COUNT(BookingID) Bookings,
SUM(BookingFare) BookingFare
FROM TaxiBookingOnline.dbo.Bookings

How to create multiple rows (as date column) into CTE? (out of thin air)

I have a stored-procedure and I want to add date column to the tables. Then I wonder how do I get MS-SQL to generate multiple rows on the fly using CTE. Say I have this..
(GETDATE() - 548) --(365 days --> 12 months, 548 days --> 18 months...
How do you guys whip up a query that would create 548 rows and have the date column as row
#1 - '12/17/2012'
#2 - '12/16/2012'
#3 - '12/15/2012'
etc. all the way to row #548? All of that into a CTE?
Thanks...
Unless I am missing something, it sounds like you want the following:
;with dates(value) as
(
select DATEADD(d, -548, cast(getdate() as DATE))
union all
select DATEADD(D, 1, value)
from dates
where DATEADD(D, 1, value) <= cast(getdate() as DATE)
)
select *
from dates
order by value desc
OPTION (MAXRECURSION 1000)
See SQL Fiddle with Demo

Can I use recursion in a Sql Server 2005 View?

I tried to use OPTION (MAXRECURSION 0) in a view to generate a list of dates.
This seems to be unsupported. Is there a workaround for this issue?
EDIT to Explain what I actually want to do:
I have 2 tables.
table1: int weekday, bool available
table2: datetime date, bool available
I want the result:
view1: date (here all days in this year), available(from table2 or from table1 when not in table2).
That means I have to apply a join on a date with a weekday.
I hope this explanation is understandable, because I actually use more tables with more fields in the query.
I found this code to generate the recursion:
WITH Dates AS
(
SELECT cast('2008-01-01' as datetime) Date
UNION ALL
SELECT Date + 1
FROM Dates
WHERE Date + 1 < DATEADD(yy, 1, GETDATE())
)
No - if you can find a way to do it within 100 levels of recusion (have a table of numbers), which will get you to within 100 recursion levels, you'll be able to do it. But if you have a numbers or pivot table, you won't need the recursion anyway...
See this question (but I would create a table and not a table-valued function), this question and this link and this link
You can use a CTE for hierarchical queries.
Here you go:
;WITH CTE_Stack(IsPartOfRecursion, Depth, MyDate) AS
(
SELECT
0 AS IsPartOfRecursion
,0 AS Dept
,DATEADD(DAY, -1, CAST('01.01.2012' as datetime)) AS MyDate
UNION ALL
SELECT
1 AS IsPartOfRecursion
,Parent.Depth + 1 AS Depth
--,DATEADD(DAY, 1, Parent.MyDate) AS MyDate
,DATEADD(DAY, 1, Parent.MyDate) AS MyDate
FROM
(
SELECT 0 AS Nothing
) AS TranquillizeSyntaxCheckBecauseWeDontHaveAtable
INNER JOIN CTE_Stack AS Parent
--ON Parent.Depth < 2005
ON DATEADD(DAY, 1, Parent.MyDate) < DATEADD(YEAR, 1, CAST('01.01.2012' as datetime))
)
SELECT * FROM CTE_Stack
WHERE IsPartOfRecursion = 1
OPTION (MAXRECURSION 367) -- Accounting for leap-years
;