Datediff function of DQL is not returning results as expected - sql

I am trying to query documentum server using DQL query. Using DATEDIFF function to select data that are created in the current date. Here is the query
SELECT title FROM content_table WHERE DATEDIFF(day, "r_creation_date", DATE(TODAY)) < '1' AND content_type IN ('story','news')
Problem is along with today's data its selecting yesterday's also. Why is less than 1 condition fetching yesterday's data also?
Have tried using DATEDIFF(day, "r_creation_date", DATE(TODAY)) = '0' but that does not fetch any result. I understand even the time comes into picture but as I am using 'day' as the date pattern will it not just calculate difference of the days alone?

You can try this query:
SELECT title FROM content_table WHERE r_creation_date > DATE(TODAY) AND content_type IN ('story','news')
if you need the objects created today (after 00:00, not in the last 24 h)

I should use the GETDATE() function to get the current day
Regards.

Related

Expanding SQL query for multiple dates

I have a SQL query that includes a __DATE__ macro. A Python script replaces this macro with the current date and then the statement is executed thus giving one day's worth of data.
For the first item selected, I would like to use tblLabTestResult.CollectionDate instead of __DATE__.
I would like to include the prior 7 days instead of just the current day.
The desired output would be something similar to:
Date,Result,Total
2021-08-28,Detected,5
2021-08-28,Not Detected,9
2021-08-29,Detected,23
2021-08-29,Not Detected,6
2021-08-30,Detected,88
2021-08-30,Not Detected,26
Current query:
SELECT
'__DATE__' as Date,
tblLabTestResult.Result as Result,
Count(tblLabTestResult.Result) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
tblLabTestResult.TestName like '%cov%'
AND tblLabTestResult.TestName not like '%aoe%'
AND tblLabTestResult.TestName not like '%antibody%'
AND tblLabTestResult.CollectionDate >= '__DATE__'
AND tblLabTestResult.CollectionDate <= '__DATE__ 11:59:59 PM'
GROUP BY
tblLabTestResult.Result;
How can I change my SQL query to accommodate these requirements? I am using MS SQL Server.
You can use DATEADD() function to get the date from 7 days ago and use all dates between date-7days and date. I have updated where condition in your query below:
SELECT
'__DATE__' as Date,
tblLabTestResult.Result as Result,
Count(tblLabTestResult.Result) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
tblLabTestResult.TestName like '%cov%'
AND tblLabTestResult.TestName not like '%aoe%'
AND tblLabTestResult.TestName not like '%antibody%'
AND tblLabTestResult.CollectionDate between DATEADD(day, -7, '__DATE__') and '__DATE__ 11:59:59 PM'
GROUP BY
tblLabTestResult.Result;
A few points:
Columns that are not aggregated must be in the GROUP BY
You should be passing your date as a parameter
Best to use a half-open interval to compare dates (exclusive end-point), so #endDate is the day after the one you want
Use short, meaningful aliases to make your code more readable
It doesn't make sense to group and aggregate by the same column. If Result is a non-nullable column then Count(Result) is the same as Count(*)
If you want to group by whole days (and CollectionDate has a time component) then replace ltr.CollectionDate with CAST(ltr.CollectionDate AS date) in both the SELECT and GROUP BY
SELECT
ltr.CollectionDate as Date,
ltr.Result as Result,
COUNT(*) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
ltr.TestName like '%cov%'
AND ltr.TestName not like '%aoe%'
AND ltr.TestName not like '%antibody%'
AND ltr.CollectionDate >= #startdate
AND ltr.CollectionDate < #endDate
GROUP BY
ltr.CollectionDate, ltr.Result;

Date automatically where clause - SQL

I have on my DB the dates that I can filter like this:
select *
where
a.y=2021 and a.m=2 and a.d=7
However if I run this query tomorrow I'll have to go there and change manually.
Is there a way to do this automatically as in if I run the query tomorrow I'll get d=8 and the day after d=9 and so on?
I tried to use get date but I get the following error:
SQL Error [6]: Query failed (#20210207_153809_06316_2g4as): line 2:7: Function 'getdate' not registered
I also don't know if that is the right solution. Does anybody know how to fix that?
you can use NOW to get the current date, and use YEAR , MONTH , DAY to get parts of the date
SELECT *
FROM [TABLE]
WHERE a.y=YEAR(NOW()) and a.m=MONTH(NOW()) and a.d=DAY(NOW())
The best solution is to have a date column in your data. Then you can just use:
where datecol = current_date
Or whatever your particular database uses for the current date.
Absent that, you have to split the current date into parts. In Standard SQL, this looks like:
where y = extract(year from current_date) and
m = extract(month from current_date) and
d = extract(day from current_date)
That said, date functions notoriously vary among databases, so the exact syntax depends on your database.
For instance, a common way to write this in SQL Server would be:
where y = year(getdate()) and
m = month(getdate()) and
d = day(getdate())

Select Query between dates not retrieving any data

I have been trying to retrieve the rows registered between two dates (since every time a person goes through a door a row is inserted). This way we get the "amount of visitors" on a monthly basis.
When querying the following:
select MOV_DATAHORA from LOG_CREDENCIAL
WHERE MOV_DATAHORA>'2017-01-01'`
a total of 5851 rows are shown. This is an example of a row:
2017-01-05 21:33:30.000
However when trying the following:
select MOV_DATAHORA from LOG_CREDENCIAL
WHERE MOV_DATAHORA>'2017-01-01'
AND MOV_DATAHORA<'2017-01-02'
0 rows are shown. I even tried the count(MOV_DATAHORA) statement but it still isn't working. I also tried with the BETWEEN statement unsuccessfully. Any ideas why?
Well... the simplest explanation based on your query predicate:
WHERE MOV_DATAHORA > '2017-01-01'
AND MOV_DATAHORA < '2017-01-02'
is that on January 1st (right after the New years) there were no visitors.
You are comparing a DateTime and a Date data types. Your table has a DateTime as you can see the 21:33:30.000 after the date, to convert and compare like types do the following.
SELECT MOV_DATAHORA FROM LOG_CREDENCIAL WHERE DATE(MOV_DATAHORA)>'2017-01-01'
AND DATE(MOV_DATAHORA)<'2017-01-02'
or using between
SELECT MOV_DATAHORA FROM LOG_CREDENCIAL WHERE DATE(MOV_DATAHORA) BETWEEN '2017-01-01'
AND '2017-01-02'

Teradata filter query to pull all data for a month

I have a query below which fetches me the data for last day of a month. In this query, ME_DT is defined as date time type. So when I do the max on ME_DT then it gives me the data for last day of a month. I think I need to convert the date time type to integer YYYYMM in a teradata filter condition, so that it gives me the data for the entire month not just for the last day of a month. How should I modify my existing query to get my desired result?
PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT =
(select max (PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT) from PADW.PL_CURR_DEFN_LOSS_FRCST_ME)
You should try to avoid calculations on a column in the WHERE-condition to get better estimates and possible index/partition-access:
with cte (dt) as
(
select max (PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT)
from PADW.PL_CURR_DEFN_LOSS_FRCST_ME
)
select ....
where PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT
between TRUNC(dt, 'mon')
and last_day(dt)
I have to use filer on the table because it has millions of records...
i did this ...but still verifying if I have got what i want...
(PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT =
(select max (cast(PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT as date format 'YYYYMM')) from PADW.PL_CURR_DEFN_LOSS_FRCST_ME))

how to get data whose expired within 45 days..?

HI all,
i have one sql table and field for that table is
id
name
expireydate
Now i want only those record which one is expired within 45 days or 30 days.
how can i do with sql query .?
I have not much more exp with sql .
Thanks in advance,
If you are using mysql then try DATEDIFF.
for 45 days
select * from `table` where DATEDIFF(now(),expireydate)<=45;
for 30 days
select * from `table` where DATEDIFF(now(),expireydate)<=30;
In oracle - will do the trick instead of datediff and SYSDATE instead of now().[not sure]
In sql server DateDiff is quite different you have to provide unit in which difference to be taken out from 2 dates.
DATEDIFF(datepart,startdate,enddate)
to get current date try one of this: CURRENT_TIMESTAMP or GETDATE() or {fn NOW()}
You can use a simple SELECT * FROM yourtable WHERE expireydate < "some formula calculating today+30 or 45 days".
Simple comparison will work there, the tricky part is to write this last bit concerning the date you want to compare to. It'll depend of your environment and how you stored the "expireydate" in the database.
Try Below:-
SELECT * FROM MYTABLE WHERE (expireydate in days) < ((CURRENTDATE in days)+ 45)
Do not execute directly! Depending of your database, way of obtaining a date in days will be different. Go look at your database manual or please precise what is your database.