Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query with a custom date range

Tags:

sql

I have a custom SQL query that returns information from "Last Month" I now need to change the date range from last month to....the 19th of the previous month to the 20th of the current month.

This is what is working to show "Last month" Can anyone help with how to modify it to show the required date range.

SELECT  TOP 10000 CONVERT(DateTime,
LTRIM(MONTH(DateTime)) + '/01/' + LTRIM(YEAR(DateTime)),
101) AS SummaryMonth,
Nodes.Caption AS NodeName,
Interfaces.Caption AS Interface_Caption,
SUM(InterfaceTraffic.In_TotalBytes) AS SUM_of_Total_Bytes_Received,
SUM(InterfaceTraffic.Out_TotalBytes) AS SUM_of_Total_Bytes_Transmitted,
SUM((NullIf(In_TotalBytes,-2)+NullIf(Out_TotalBytes,-2))) AS SUM_of_TotalBytesRecvXmit,
Interfaces.Gig_Limit AS Gig_Limit,
SUM((NullIf(In_TotalBytes,-2)+NullIf(Out_TotalBytes,-2))) - (Interfaces.Gig_Limit *    1073741824)  AS Diff

FROM 
(Nodes INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID))  INNER JOIN        InterfaceTraffic ON (Interfaces.InterfaceID = InterfaceTraffic.InterfaceID AND InterfaceTraffic.NodeID = Nodes.NodeID)


WHERE 
( DateTime >= dateadd(mm,datediff(mm,0,getdate())-1,0) AND DateTime
<dateadd(mm,datediff(mm,0,getdate()),0) )
 AND  
(
  (Interfaces.Caption LIKE '%SM%') OR 
  (Interfaces.Caption LIKE '%County Snow%')
)


GROUP BY CONVERT(DateTime, LTRIM(MONTH(DateTime)) + '/01/' + LTRIM(YEAR(DateTime)),   101), 
Nodes.Caption, Interfaces.Caption, Interfaces.Gig_Limit

Having SUM((NullIf(In_TotalBytes,-2)+NullIf(Out_TotalBytes,-2))) - (Interfaces.Gig_Limit * 1073741824) > 0


ORDER BY SummaryMonth ASC, 6 DESC

Thanks Dave

like image 775
user1744193 Avatar asked Sep 14 '26 23:09

user1744193


1 Answers

WHERE (DateTime >= 18+dateadd(mm,datediff(mm,0,getdate())-1,0)
  AND  DateTime <  19+dateadd(mm,datediff(mm,0,getdate()),0))

I'm taking you literally, i.e. 19th of LAST to 20th of CURRENT, although it would probably make more sense from 20th-last to 19th current. It's easy to tweak the numbers though.

like image 144
RichardTheKiwi Avatar answered Sep 17 '26 21:09

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!