Querying result from select part of statement - sql

I have a stored procedure to work out how many working days between two dates
select
casekey, LoginName, casestartdatedate,
dbo.CalcWorkDaysBetween(casestartdatedate, GETDATE()) AS 'WD'
from
Car_case with (nolock)
where
dbo.CalcWorkDaysBetween(casestartdatedate, GETDATE()) <= DATEADD(dd,DATEDIFF(dd, 0, GETDATE()), -60)
and CaseClosedDateDate is null
order by
CaseStartDateDate asc
In my select part of statement I want to show the number of working days between the case start date and today's date. This part is fine. But I only want to return cases where the 'working days' is 60 days or greater - I'm having trouble with this part of query. See my code above. not too sure why its not working. It's returning results less than and greater than 60 days making me realize I've gone wrong somewhere.
Any help would be appreciated!

If I understand correctly, you just need to fix the where condition:
select casekey, LoginName, casestartdatedate,
dbo.CalcWorkDaysBetween(casestartdatedate, GETDATE()) AS WD
from Car_case cc with (nolock)
where dbo.CalcWorkDaysBetween(casestartdatedate, GETDATE()) >= 60 and
CaseClosedDateDate is null
order by CaseStartDateDate asc;
Note: In your version you are comparing the result of the function (which is presumably an integer) to a date.

Related

SQL - Find value for the last 5 weeks and the next 5 weeks in the same query

I need to find inventory values for the last 5 weeks and the next 5 weeks on any given day I run the query (going to connect to Excel and run daily).
I am able to find them individually but when done together I get no returns.
The following work individually, is there a way to combine and get all returns?
Select * FROM Table
WHERE vdvInventory.Count >= CAST(DATEADD(WEEK, -5, GETDATE()) as DATE)
alternatively
Select * FROM Table
WHERE DATEDIFF(WEEK,vdvInventory.Count,GETDATE() )<5
If I try adding both where statements into one with an ADD I get no returns.
For Example:
Select * FROM Table
WHERE DATEDIFF(WEEK,vdvInventory.Count,GETDATE() )<5
AND DATEDIFF(WEEK,vdvInventory.Count,GETDATE() )>5
Thanks for any help or guidance with this!
Your query doesn't work because you have a contradictory statement: same expression (DATEDIFF(WEEK,vdvInventory.Count,GETDATE())) cannot be less and greater than 5 at the same time.
Try instead the following:
Select * FROM Table
WHERE vdvInventory.Count >= CAST(DATEADD(WEEK, -5, GETDATE()) as DATE)
and vdvInventory.Count <= CAST(DATEADD(WEEK, 5, GETDATE()) as DATE)

How to create time slots of the day in SQL server

I apologize in advance if you think the question has already been answered, I searched on Stack, but similar answers were much too complex for me.
I have this request in SQL :
SELECT dbo.tbTransaction.dateHeure, dbo.tbPoste.nomPoste
FROM dbo.tbTransaction
INNER JOIN dbo.tbPoste ON dbo.tbTransaction.ID_poste = dbo.tbPoste.ID_POSTE
WHERE dbo.tbPoste.id_site LIKE 17
AND dbo.tbPoste.nomPoste LIKE 'POSTE1'
AND dateHeure >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
ORDER BY dateHeure DESC
It gives me all the production of the day, the problem is : it's not precise enough because there is a team shift in the afternoon and another team shift in the night.
If you see all the production of the day, you cannot see which team produced what.
I would like to create 3 different queries that allow me to see only the production between certain hours (for example, production between 6am and noon). Do you have any advice on how to do this?
I think you will have to hardcode your time slots. For example you know that morning shift is going to work from 06:00 to 12:00.
As you know the hours, you can use HOUR function on your datetime column with appropriate >, <, = and AND operators to get the required results.
From what I have understood, it should be something like this:
HOUR(datetime column) >= 6 AND HOUR (datetime column) < 12
Okay I managed to find the query I wanted :
SELECT dbo.tbTransaction.dateHeure, dbo.tbPoste.nomPoste FROM dbo.tbTransaction INNER JOIN dbo.tbPoste ON dbo.tbTransaction.ID_poste = dbo.tbPoste.ID_POSTE WHERE dbo.tbPoste.id_site LIKE 17
AND dbo.tbPoste.nomPoste LIKE 'POSTE1'
AND dateHeure >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
AND DATEPART(HOUR, dateHeure) > 6
AND DATEPART(HOUR, dateHeure) < 13
ORDER BY dateHeure DESC

In Microsoft SQL Server, how to split rows using datetime data

As I am working on a project for my university, I am supposed to create a dashboard for machines downtime.
Every time that a machine is down during the day, the availability is calculated as [ 24 (hours) - Downtime / 24 (hours) ].
However, there are some situations where the machines are down more than 1 day, so it means that I have the split the number of hours that machine is down and distributed to the respective days.
Here is what the data looks like:
Here is what the result looks like:
My idea,
Create one temp table with number between specific range by SELECT DISTINCT SeqDateDiff = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 1000.
PS: the range is 0 to 1000 in the sample, you can create wider range, but it should not be neccessary, you can consider remove the machine if already down over 1000 days. And there are some other methods to create this kind of range table, you can google it.
Then left join with your table with date difference by on target.DateDiff+1>seq.SeqDateDiff.
Then the rest is simple, just calculate out reported/completed based on different situations.
Check working sample at SQL fiddler.
Below is the codes:
select ServiceID,
case when SeqDateDiff>0 then cast(DATEADD(day, SeqDateDiff, Reported) As Date) else Reported end Started,
case when SeqDateDiff=DateDiff
then Completed
else DATEADD(second, -1, cast(cast(DATEADD(day, SeqDateDiff+1, Reported) As Date) as DateTime))
end Completed,
DateDiff, SeqDateDiff
from (select ServiceID, Completed, Reported, DATEDIFF(day, Reported, Completed) DateDiff from YourTable) target
left join (
SELECT DISTINCT SeqDateDiff = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 1000
) seq on target.DateDiff+1>seq.SeqDateDiff
select case when datediff(hh, reported, completed)>12 then 12 else
datediff(hh, reported, completed) end from yourtable
if day(reported)<>day(completed)
begin
select datediff(hh, cast(completed as date), completed) from yourtable
end
Assuming it's never down more than 2 days. If so, adjust logic accordingly...

DATEPART function assigning

I have table who order a order today and yesterday (18,17)
I need to find those result .
select A.C_Name
from Customer_Table A
inner join
Order_Table O
On A.C_ID=O.C_ID
where DATEPART(DAY,Order_Date)=GetDATE() and
DATEPART(DAY,Order_Date)=GETDATE()-1
I didnt get result for above query .
If you want orders today and yesterday, then this should be sufficient:
where Order_Date >= dateadd(day, -1, cast(getdate() as date))
(This assumes no future order dates, which seems reasonable).
Your query is a mess for several reasons. datepart() returns an integer and you are comparing it to a date. Looking at just the "day" part of a date will not work on the first of the month. And, getdate() -- despite its name -- has a time component, so direct equality is inappropriate.

SQL - Syntax for data within X number of days pulls all data

I have a query I need to run regularly which pulls errors from a log table for x number of days. I originally found the syntax for the x number of days on here highlighted below with --<<.
The script pulls the information I want, throws no errors, but it pulls items from all dates not just past X days I am looking for. No matter what value I place before ...,getdate()) it pulls all the records.
Any Ideas how to get it to correctly give me the date range from today that I am looking for?
SELECT
t2.[campaignshortname],
t1.[CampaignId],
t1.[CreatedDtTm],
t1.[Msg],
t1.[ReferenceDate]
FROM
[alchemy].[CM].[CampaignLog] AS t1 (nolock)
INNER JOIN
[alchemy].[CM].[Campaign] AS t2 ON t1.CampaignId = t2.Id
WHERE
CAST(t1.[ReferenceDate] AS DATE) <= dateadd(DAY, -30, getdate()) --<<
AND t1.Msg LIKE '%fail%' OR t1.Msg LIKE '%error%'
ORDER BY
ReferenceDate DESC
I would actually change the query a little bit more and use between:
where convert(datetime, t1.[ReferenceDate]) between getdate()-30 and getdate()
and (t1.Msg like '%fail%' or t1.Msg like '%error%')
Although those to likes will cause a full scan of either index or table unless you subquery it.
You need to enclose your t1.Msg like '%fail%' or t1.Msg like '%error%' in parentheses, as and precedes or in execution order. As is, your condition searches in your table first rows where the date is 30 days or more before current date and message contains the word "fail", and then it searches in your table the rows where the message contains the word "error". Your condition then should be:
where CAST(t1.[ReferenceDate] AS DATE) <= dateadd(DAY, -30,getdate())
and (t1.Msg like '%fail%' or t1.Msg like '%error%')