CASE Statement with Dates in WHERE Clause - sql

I am trying to write a WHERE clause to look back 3 days when the day of the week is Monday by joining in the calendar table.
WHERE
CASE WHEN calendar.DW = 2 Then (date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-3))
AND GETDATE() ELSE
date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-1))
AND GETDATE()
END
I am getting an error on the "BETWEEN" operator for the above. Is it possible to do what I am attempting, or am I going about this in the wrong manner?
Thanks for the help.

You need to add a condition which can be evaluated to true or false, like so:
WHERE
(CASE WHEN calendar.DW = 2 AND date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-3))
AND GETDATE() THEN 1 WHEN
date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-1))
AND GETDATE() THEN 1 ELSE 0
END) = 1

You could try a simple where clause:
WHERE calendar.DW = 2 AND
date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-3)
AND GETDATE()
OR
date_created BETWEEN DATEADD(hour,8,DATEDIFF(d,0,GETDATE()-1))
AND GETDATE()

Related

SQL if statement for date range

Hi I was needing help with the syntax to add a condition where the current date is retrieved if today is after the 5th of each month but if its between the 1st to the 5th then it should retrieve the month before this month. Is it something you can help with please? Below is how my query is structured.
Select *
FROM table1
left join table2
on e.ENTITY_NBR = d.entity_nbr
and cast(getdate() as date) between MONTH_BEGIN_DATE and MONTH_END_DATE
Select *,
CASE WHEN day(GETDATE()) > 5 THEN GETDATE()
ELSE DATEADD(month,-1,getdate()) END as date
FROM table1
left join table2
on e.ENTITY_NBR = d.entity_nbr
and cast(getdate() as date) between MONTH_BEGIN_DATE and MONTH_END_DATE
Based on a vague description of your problem this is the best I can write.
If you simply want to include todays date (or the same date from last month if it's currently the 5th or earlier in the current month), then this can be done in your SELECT clause:
select
case
when datepart(day,getdate()) <= 5
then dateadd(month,-1,getdate())
else getdate()
end
If you want to actually use this date to compare to some field in your dataset, then you can include this same case expression in your WHERE clause.
where the current date is retrieved if today is after the 5th of each month but if its between the 1st to the 5th then it should retrieve the month before this month.
Based on this description, you want something like this:
select *
from table1 e left join
table2 d
on e.ENTITY_NBR = d.entity_nbr and
(day(getdate() > 5 and datediff(month, d.date_col, getdate()) = 0 or
day(getdate() <= 5 and datediff(month, d.date_col, getdate()) = 1)
)

How to calculate days count between 2 date in sql server

I'm creating a system to calculate user working days.
Suppose user 1 has been at work from 2020-02-01 to 2020-02-20.
And user 2 has been at work from 2020-02-10 to 2020-02-15
In Sql Server
I have something similar in the table below
Now i want to calculte count of user working days between 2 date
For Example
Select Sum(DateDiff(Day,StartDate,EndDate)) From Table1 Where StartDate >= '2020-02-08' And EndDate <= '2020-02-12'
Above query returns 0 . But in this date user 1 has 5 working days and user 2 has 3 working days.
How can i calculate this?
I want a similar answer below:
You can use datediff() -- after testing for the limits of the period that you want:
select t.*,
datediff(day,
case when startdate < '2020-02-08' then '2020-02-08' else startdate end),
case when enddate > '2020-02-12' then '2020-02-12' else startdate end)
) + 1
from t;
The + 1 is because you are including the last day in the calculation.
Note: This only works correctly when there is an overlap. You want a filter:
(enddate >= '2020-02-08' or startdate <= '2020-02-12')
Based on the question, I'm not sure if this should be in a WHERE clause or a CASE expression. That is, do you want to filter out non-overlaps or do you want them to appear as 0/NULL?

Trying to a Select Count where it needs to count the difference between a certain date and current date

It's not quite working for me!
My query is as follows:
SELECT COUNT (*) as [generic]
FROM [Log]
Where value IN (Select ID, tsSendDocument, sysReceivedFrom
WHERE sysReceivedFrom = 'generic' AND
DATEDIFF(hour, tsSendDocument, GetDate()) > 2)
So, what am I doing wrong here?
I want it to to count every time the tsSendDocument column is older than 2 hours. It will eventually give me a count that's equal to 1. I have a table set up to alert me if the value = 1, which means that the tsSendDocument is older than 2 hours.
Do this make any sense?
As per your comment, I've understood that you want to check if the last entry is older than 2 hours, so this should work:
SELECT TOP 1 CASE WHEN tsSendDocument < DATEADD(HOUR, -2, GETDATE()) THEN 1 ELSE 0 END AS [generic]
FROM [Log]
ORDER BY tsSendDocument DESC
I think you want only aggregation :
Select COUNT(*)
FROM Log
WHERE sysReceivedFrom = 'generic' AND
DATEDIFF(hour, tsSendDocument, GetDate()) > = 2;
subquery will only return one expression when you specified IN orNOT IN clause.

Get count of rows where date is less than today

I have done the following to get a list of count for today having a date less than today. I have done the following code:
select SUM(CASE WHEN (EXPIRYDAYE>= CONVERT(date, GETDATE())) > 1
then 1
else 0
end)
from bottles;
However, I am getting this as error:
Incorrect syntax near '>'.
Note that I need to do the count that way. So please help me on the syntax in this way of doing the count. Thanks
you have to try like below
select SUM(CASE WHEN EXPIRYDAYE< CONVERT(date, GETDATE()) then 1 else 0 end)
In your sql query case when statement is wrong
CASE WHEN (EXPIRYDAYE>= CONVERT(date, GETDATE())) > 1 -- here last >1 is illogical
Try this
SELECT
SUM(
CASE WHEN EXPIRYDAYE< CAST(GETDATE() AS DATE)
THEN 1
ELSE 0 END)
You don't need the > symbol before the 1
Following simple query should work for your case. You don't need CASE WHEN for this.
SELECT COUNT(*) TotalCount
FROM YOUR_TABLE WHERE EXPIRYDAYE < CAST(GETDATE() AS DATE)
Note that I need to do the count that way. So please help me on the
syntax in this way of doing the count.
I am not sure why you want to do it in a specific way whereas more efficient query is available.

Comparing dates using SQL

I have a date that looks like this: 2014-10-01 12:35:29.440
the table looks like this:
ORDER 1 | 2014-07-31 00:00:00.000
ORDER 2 | 2015-07-31 00:00:00.000
sorry i wanted ORDER 2 to show up.. As my get date returns todays date and that is GREATER than 2014-07-31 00:00:00.000
Here is what i have tried:
SELECT TOP 1 NAME
FROM ORDER_DATES
WHERE GETDATE() > ORDER_DATE
ORDER BY NAME DESC
Your question still isn't quite worded in a way that is conducive to what you need... but I think I understand what you want now based on the comments.
Based on the comment:
IF it doesnt match the date then it needs to return the next row.
Which is ORDER 2
Something like this should work:
SELECT TOP 1 name
FROM ORDER_DATES o
INNER JOIN (
-- This subquery finds the first date that occurs *after* the current date
SELECT MIN(ORDER_DATE) AS ORDER_DATE
FROM ORDER_DATES
WHERE ORDER_DATE > GETDATE()
) minDateAfterToday ON o.ORDER_DATE = minDateAfterToday.ORDER_DATE
ORDER BY name
This would work a lot better if you had an ID field in the table, but this should work with the given data, you'll potentially run into issues if you have two orders on the exact same date.
EDIT:
here's a fiddle showing the query in action:
http://sqlfiddle.com/#!6/f3057/1
DATEDIFF will come handy, also you have to order by ORDER_DATE:
SELECT TOP 1 NAME
FROM ORDER_DATES
WHERE DATEDIFF(DAY,ORDER_DATE,GETDATE())>0
ORDER BY ORDER_DATE DESC
You can write as:
SELECT NAME
FROM ORDER_DATES
WHERE cast(GETDATE()as date) > cast (ORDER_DATE as date)
ORDER BY NAME DESC
Demo
Check if you are querying against right table
declare #dt datetime = cast('2014-10-01 12:35:29.440' as datetime), #dt2 datetime= cast('2014-07-31 00:00:00.000' as datetime);
print(case when #dt > #dt2 then 1 else 0 end);
This piece of script shows output 1 i.e. condition should match for ORDER 1.
Verify if you are missing some thing.
Edit as per change to original question:
here the condition needed be reverted as date value is in future which is greater than current date
new query will be as
SELECT TOP 1 NAME
FROM ORDER_DATES
WHERE ORDER_DATE > GETDATE()
ORDER BY NAME DESC