SQL query to show data only for today? - sql

I would like to automate a query without anyone changing the date manually. I have tried "GETDATE()" to no avail. I plan to use Google Sheets script editor to automate this task.
Here's a portion of the code where we change the date manually:
Left Join
OrderType ON SalesOrder.OrderTypeID = OrderType.OrderTypeID
Left Join
Location On EventRef.LocationID = Location.LocationID
Inner Join
Client On Location.ClientID = Client.ClientID
Inner Join
RequestSource On SalesOrder.RequestSourceID = RequestSource.RequestSourceID
WHERE
EventRef.EventDateTime > '11-Oct-21 0:00:00 AM'
AND EventRef.EventDateTime < '11-Oct-21 23:59:59 PM'
AND OrderStatus.OrderStatusName <> 'Added in error'
AND OrderStatus.OrderStatusName <> 'Cancelled;

GETDATE/SYSDATETIME or GETUTCDATE/SYSUTCDATETIME or even SYSDATEIMEOFFSET (which depends on your data) is what you want and some very simply date logic:
...
WHERE EventRef.EventDateTime >= CONVERT(date, GETDATE())
AND EventRef.EventDateTime < CONVERT(date, DATEADD(DAY, 1, GETDATE()))
...

Related

SQL Server Yesterdays Count

I am trying to get a count of all of yesterdays rows. The query i have runs good but does not pick up null values. Is there a way i can query a count of null and non null values?
Here is my code:
SELECT dateadd(day,datediff(day,0,GETDATE())-1,0) as Received_Date,
COUNT(*) as Enrollments_Completed
FROM Table CD,
CCMDB.dbo.ResolutionLetterDetails RD
WHERE CD.ccid = RD.ccid
and CompletedDate >= DATEADD(d,DATEDIFF(d,1,getdate()),0)
and CompletedDate < DATEADD(d,DATEDIFF(d,0,getdate()),0)
AND CatID in('cat0014')
AND IncomingType <> 'RITS'
AND status = 'Completed'
Convert your CompletedDate to a date with no time and make it equal yesterdays date with no time (from GETDATE()) and use correct JOIN code.
SELECT dateadd(day,datediff(day,0,GETDATE())-1,0) as Received_Date,
COUNT(*) as Enrollments_Completed
FROM Table CD
LEFT JOIN CCMDB.dbo.ResolutionLetterDetails RD ON CD.ccid = RD.ccid
WHERE dateadd(day,datediff(day,1,CompletedDate),0) = dateadd(day,datediff(day,1,GETDATE()),0)
AND CatID IN ('cat0014')
AND IncomingType != 'RITS'
AND status = 'Completed'
Return NULLs:
SELECT dateadd(day,datediff(day,0,GETDATE())-1,0) as Received_Date,
COUNT(*) as Enrollments_Completed
FROM Table CD
LEFT JOIN CCMDB.dbo.ResolutionLetterDetails RD ON CD.ccid = RD.ccid
WHERE dateadd(day,datediff(day,1,CompletedDate),0) = dateadd(day,datediff(day,1,GETDATE()),0)
AND (CatID IN ('cat0014') OR CatID IS NULL)
AND (IncomingType != 'RITS' OR IncomingType IS NULL)
AND (status = 'Completed' OR status IS NULL)
I would fix your query and do:
SELECT CAST(DATEADD(day, -1, GETDATE()) as DATE) as Received_Date,
COUNT(*) as Enrollments_Completed
FROM Table CD JOIN
CCMDB.dbo.ResolutionLetterDetails RD
ON CD.ccid = RD.ccid
WHERE CompletedDate >= CAST(DATEADD(day, -1, GETDATE()) as DATE) AND
CompletedDate < CAST(GETDATE() as DATE) AND
CatID IN ('cat0014') AND
IncomingType <> 'RITS' AND
status = 'Completed';
For the date part, you could also do:
CAST(CompletedDate as DATE) = CAST(DATEADD(day, -1, GETDATE()) as DATE)
This version is even index-safe in SQL Server (although not necessarily in other databases).
Notes:
The DATE data type considerably simplifies your calculations.
Never use commas in the FROM clause. Always use proper, explicit, standard JOIN syntax.
You should qualify all column names so you (and anyone reading the query) knows what table the column comes from.

Get the DueDate if the date is today

I am assigned to create an alert that if today is the duedate of an item, then the alert will be sent to the team.
I am trying to check how I can filter the where clause of my code:
SELECT dbo.salesorder.customerid,
dbo.salesorder.entrydate,
dbo.salesorder.salesorderno,
dbo.salesorderdetails.itemno,
dbo.salesorder.usercreated,
dbo.salesorder.duedate
from dbo.salesorder
inner JOIN dbo.salesorderdetails
ON dbo.salesorder.salesorderid = dbo.salesorderdetails.salesorderid
where (dbo.salesorder.customerid = 238)
If today is 4th of May, I just my report to display the below-highlighted sales orders.
convert getdate() to date and compare with the duedate
where (dbo.salesorder.customerid = 238)
and dbo.salesorder.duedate = convert(date, getdate())
SELECT dbo.salesorder.customerid,
dbo.salesorder.entrydate,
dbo.salesorder.salesorderno,
dbo.salesorderdetails.itemno,
dbo.salesorder.usercreated,
dbo.salesorder.duedate
from dbo.salesorder
inner JOIN dbo.salesorderdetails
ON dbo.salesorder.salesorderid = dbo.salesorderdetails.salesorderid
where dbo.salesorder.duedate = CAST(GETDATE() AS DATE) --or CAST(CURRENT_TIMESTAMP AS DATE)
and dbo.salesorder.customerid = 238

sql with group by and range of dates

I have a query which uses max aggregate function to calculate reset date for a particular selection date.There is a table vp_Accrual which have effectivedate field.selection date is passed to effectivedate field and based on that using Max function, reset date is calculated.This Query gives result only for a particular selection date.It calculate a reset date based on selection date passed.
I want to modify it so that it will give me reset date for a range of dates
Below Query gives Output for one person for the date 1st Jan as follow.
We need to modify Query so that it will give result for multiple selection date instead of only one selection date.
I tried by adding addition #enddate field as effectivedate between #selectiondate and #enddate.
But I guess tha approach is not correct.
I want to pass range of date, such as 1st jan to 4th Jan, and it should give Output for each date as below
[Image is added as Link as i dont have enough Repuation Point][https://i.stack.imgur.com/0HSX1.jpg]
Below is the Query used.
DECLARE #selectionDate datetime
SET #selectionDate = CONVERT(nvarchar(10), DATEADD(dd, 0, CAST('01/01/2017' AS datetime)), 101)
SELECT
e.personnum,
ac.name as Accrul_Code,
#selectionDate as Selection_DATE,
CASE
WHEN MAX(va.effectivedate) IS NULL THEN CAST('1/1/1753' AS datetime)
ELSE MAX(va.effectivedate)
END AS resetdate
FROM vp_employeev42 e WITH (NOLOCK)
INNER JOIN accrualprofile ap
ON e.accrualprflname = ap.name
INNER JOIN accrualprofilemm apm
ON apm.accrualprofileid = ap.accrualprofileid
INNER JOIN accrualrule ar
ON apm.accrualruleid = ar.accrualruleid
INNER JOIN accrualcode ac
ON ac.accrualcodeid = ar.accrualcodeid
LEFT OUTER JOIN vp_accrual va
ON va.accrualcodeid = ar.accrualcodeid
AND e.personid = va.personid
AND accrualtrantype IN (3, 11)
AND va.effectivedate <= #selectionDate
WHERE
ac.NAME IN ('FT PTO','LOC','EPT - 5','PT PTO','EPT')
AND va.DISQUALIFIEDSW != 1
and e.PERSONNUM='00152'
GROUP BY e.personnum,
ac.name
Please help me with this Query
Best I can make out, you want a Cartesian join on a fake date table that will cause your results to repeat themselves over and over, but for a different set of dates each time
Something like this:
DECLARE #selectionDate datetime
DECLARE #endDate datetime
SET #selectionDate = DATEFROMPARTS(2017,1,1)
SET #endDate = DATEFROMPARTS(2017,5,1)
WITH dates ( IncDate ) AS (
SELECT #selectionDate UNION ALL
SELECT DATEADD(month,1,IncDate) FROM dates WHERE Incdate <= #endDate )
SELECT
e.personnum,
ac.name as Accrul_Code,
IncDate as Selection_DATE,
MAX(COALESCE(effectivedate, CAST('1/1/1753' AS datetime)) AS resetdate
FROM vp_employeev42 e WITH (NOLOCK)
INNER JOIN accrualprofile ap
ON e.accrualprflname = ap.name
INNER JOIN accrualprofilemm apm
ON apm.accrualprofileid = ap.accrualprofileid
INNER JOIN accrualrule ar
ON apm.accrualruleid = ar.accrualruleid
INNER JOIN accrualcode ac
ON ac.accrualcodeid = ar.accrualcodeid
CROSS JOIN dates
LEFT OUTER JOIN vp_accrual va
ON va.accrualcodeid = ar.accrualcodeid
AND e.personid = va.personid
AND accrualtrantype IN (3, 11)
AND effectivedate <= IncDate
WHERE
ac.NAME IN ('FT PTO','LOC','EPT - 5','PT PTO','EPT')
AND va.DISQUALIFIEDSW != 1
and e.PERSONNUM='00152'
GROUP BY e.personnum,
ac.name,
IncDate
A few cautions though:
This query cannot generate the results you posted, but neither can yours. There's no logic at all to your example results, where your reset date is the max date that is less than the selection date but your first of February selection date somehow chooses the tenth of Jan, yet your first of march selection date chooses the eleventh of Jan.
This is totally untested; you provided no sample data, only an image of the results, and I post from an iPad, so generating test data would be incredibly laborious, typing it all in
You mix up your dates as varchar and datetime. Please be more diligent in keeping these data types separate. Always work with dates as dates, not strings. Never store dates as string. Never rely on implicit conversions between date and string
DATEFROMPARTS came along in sqlserver 2012 I think, if your sql is older than this, use convert with a format string to turn your string into a date.. do not declare selectiondate as a varchar!

How can I optimize my query?

I wrote this code that find the down nodes and calculate the up and down hours. This code works but I want to know any other way or optimize of this code? what is the best way to calculate the duration of down time? and Is there any way(interactive way) that user can input the date and time interval?
SELECT q1.nodeid, q1.VendorIcon, q1.Caption, q1.IP_Address,
q1.OutageDurationInMinutes,
q2.TimeUp
FROM
(SELECT
Nodes.NodeID AS NodeID, ltrim(rtrim(Nodes.Caption)) Caption, Nodes.VendorIcon,Nodes.IP_Address,
sum(DATEDIFF(hh, StartTime.EventTime, EndTime.EventTime)) as OutageDurationInMinutes
FROM Events StartTime
Left join Events EndTime On
EndTime.EventType = '5' and
EndTime.NetObjectType = 'N' and
EndTime.NetworkNode = StartTime.NetworkNode and
EndTime.EventTime =
(
Select
min(EventTime)
from Events
where
EventTime>StartTime.EventTime and
EventType = '5' and
NetObjectType = 'N' and
NetworkNode = StartTime.NetworkNode
)
INNER JOIN Nodes ON
StartTime.NetworkNode = Nodes.NodeID
WHERE
Nodes.Department = '4' AND
StartTime.EventType = 1 AND
StartTime.NetObjectType = 'N' AND
StartTime.eventtime between dateadd(M, -1, getdate()) and getdate()
Group by
Nodes.NodeID,Nodes.Caption, Nodes.VendorIcon,Nodes.IP_Address, Nodes.LastBoot
) q1
INNER JOIN
(SELECT
Nodes.NodeID AS NodeID
,ltrim(rtrim(Caption)) Caption
,VendorIcon
,Ip_Address
,DateDiff(hour,Nodes.LastBoot,GetDate()) AS HoursUp
,CONVERT(VARCHAR(40), DATEDIFF(minute, Nodes.LastBoot, GETDATE())/(24*60))
+ ' days, '
+ CONVERT(VARCHAR(40), DATEDIFF(minute, Nodes.LastBoot, GETDATE())%(24*60)/60)
+ ' hours, and '
+ CONVERT(VARCHAR(40), DATEDIFF(minute, Nodes.LastBoot, GETDATE())%60)
+ ' minutes.' AS TimeUp
FROM [Nodes]
Where
LastBoot between dateadd(day, -30, getdate()) and getdate()) q2 on q1.NodeID=q2.NodeID
Order by Caption
I want to know any other way or
optimize of this code?
I would recommend having a look at the query execution plan for you query.
Is there any way(interactive way) that
user can input the date and time
interval?
You could just determine the values before you run the query and use these parameters in your query (I'm not sure what's calling your query though, is it a stored procedure?)

MS Access Query problem?

I am using this query:
SELECT D.Generic, D.Ww, D.Dd, D.Plan, c.TotalScan, D.Plan - c.TotalScan AS Balance
FROM TableA D
LEFT JOIN (
SELECT COUNT(a.Specific) AS TotalScan,
b.Generic, a.Dd,a.Ww
FROM TableB a
INNER JOIN TableC b
ON a.Specific = b.Specific
GROUP
BY b.Generic,a.Dd,a.Ww
WHERE DATEDIFF(DAY, a.TransactionDate, GETDATE()) = 0
) c
ON c.Generic = D.Generic
AND D.Ww = c.Ww
AND c.Dd = D.Dd
WHERE DATEDIFF(DAY, c.TransactionDate, GETDATE()) = 0;
to filter all records that is a insert in my sqlserver database.
Now i am having a hard time how can i do it ms access.
1. DATEDIFF(Day, TransactionDate, GetDate()) = 0 -- Not Work on MS Access(Which Filter all Records inserted in current Date)
2. Cant display TotalScan from subquery
Example Output Date:
TransactionDate
3/21/2011 7:26:24 AM
3/21/2011 7:26:24 AM
3/22/2011 7:26:24 AM --
3/22/2011 7:26:28 AM --
3/22/2011 7:26:30 AM --
3/22/2011 7:26:32 AM --
3/22/2011 7:26:35 AM --
if my date today is 3/22/2011 5 records will be displayed.
Thanks in Regards
GetDate() is SQL Server specific, Access has Now() instead.
The DateDiff() function also exists in Access, but the parameter for the interval is different:
DateDiff("d", TransactionDate, Now())
Equivalent of:
DATEDIFF(DAY, c.TransactionDate, GETDATE()) = 0
DATEDIFF("d", c.TransactionDate, Now()) = 0
Regards