Select dates inside current month SQL - sql

I have a table similar to one below. I'm trying to select only the rows where the Start Date is in the current month. Here is what I have so far, but it's not working.
SELECT *
FROM TABLE1
WHERE StartDate = MONTH(getdate())
How can I select only the values where the start date is in the current month?

Use this construct to avoid functions on the StartDate columns (like MONTH or YEAR). These functions will prevent any index or statistics being used/
SELECT *
FROM TABLE1
WHERE
StartDate >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND StartDate < DATEADD(month, 1+DATEDIFF(month, 0, GETDATE()), 0)
Any answer that puts a function on StartDate will not scale as expected. See error number 2 here. The filter is now non-sargable, and index/statistics can't be used. Every row will be looked at for a table scan.

You need to check the month of both fields
WHERE MONTH(startdate) = MONTH(getdate())

Related

SQL getdate issue with month

i need help on my little problem.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
WHERE Day(ServiceDate) BETWEEN '1' AND Day(getdate() -2)
AND Month(ServiceDate) =
CASE
WHEN Day(getdate()) <=2
THEN Month(getdate() -1
ELSE Month(getdate())
END
AND Year(ServiceDate) = Year(getdate())
Now the problem is the first and the second of the Month.
The query don't use the last month. It shows the actual month.
I hope its clear what i need.
if we have the 01-06-2016 and i need minus 2, so the query must give me back to the day 30-05-2016
big THX
the output for today with this query
output query
Assuming you are using sql-server, you need to use DATEADD(Day, -2, GETDATE()) for subtracting 2 days from current date.
I think I understand the logic now:
If the current day is the 1st of the month, get all the records from the start of previous month, until 2 days before it ends.
If the current day is the 2nd of the month, get all the records from the start of the previous month until one day before it ends.
If the current day is the 3rd of the month or higher, get all the records from the beginning of the current month until 2 days ago.
Since you are using the FORMAT() function that was introduced in 2012 version, you can also use the EOMONTH() function that was introduced in the same version.
This function returns the date of the end of the month of the date it receives as an argument, and also have a useful optional second argument that specifies the numbers of months to add to the date passed to the function.
Using this function will allow you to write your query without using any functions on the ServiceDate column, thus enabling the use of any indexes defined on this column.
DECLARE #Now datetime = GETDATE()
SELECT FORMAT(ServiceDate, 'dd-MM-yyy') AS ServiceDate
FROM Services
WHERE (
DAY(#Now) <= 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -2))
AND ServiceDate < DATEADD(DAY, -(DAY(#Now)-1), EOMONTH(#Now, -1))
)
OR
(
DAY(GETDATE()) > 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -1))
AND ServiceDate < DATEADD(DAY, -2, #Now)
)
Compute enddate as 2 days before getdate() and select data in interval from enddate's first of month and enddate.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
CROSS APPLY (SELECT enddate = DATEADD(D,-2,getdate()) x
WHERE ServiceDate BETWEEN DATEADD(MONTH,DATEDIFF(MONTH,0,x.enddate),0) AND x.enddate

DATEADD conditon take long time in SQL Server 2008 .Why?

I would like to get data between previous month and current month in my sale table. I use the dateadd function to get month. But the query take long time to return result. When I remove date range in where clause, execution time is very fast. How can I add date range for month to fast execution time in query?
Here is my query.
select *
from sales S
where S.DOCUMENT_DATE >= DATEADD(m, DATEDIFF(m, 0, GETDATE())-1 , 0) and
S.DOCUMENT_DATE <= DATEADD(m, DATEDIFF(m, 0, GETDATE())+1 , -1)
Given your query, you want an index on sales(document_date).
You could create a Nonclustered Index.
CREATE NONCLUSTERED INDEX NC_IX_Sales_DOCUMENT_DATE ON Sales (DOCUMENT_DATE)
Then you could run your query.
SELECT *
FROM Sales s
WHERE s.DOCUMENT_DATE >= DATEADD(mm,DATEDIFF(mm,0,DATEADD(mm,-1,GETDATE())),0)
AND s.DOCUMENT_DATE <= DATEADD(ms,-3,DATEADD(mm,DATEDIFF(m,0,getdate())+1, 0))
Also you could take in account that current month has not ended yet.
SELECT *
FROM Sales s
WHERE s.DOCUMENT_DATE >= DATEADD(month,DATEDIFF(month,0,DATEADD(month,-1,GETDATE())),0)
AND s.DOCUMENT_DATE <= GETDATE()

Select all where date in Last month sql [duplicate]

This question already has answers here:
Get the records of last month in SQL server
(23 answers)
Closed 9 years ago.
How can I get last month date like
select * from table where date in ( last month )
I dont want the last 30 days
AND how can I get last month automatically
Assuming you want all items where the date is within the last month i.e. between today and 30/31 days ago:
Select *
From Table
Where Date Between DATEADD(m, -1, GETDATE()) and GETDATE()
You can use this
Select * from table where date between #startdate and #enddate
Or
SELECT * FROM DATE_SAMPLE WHERE
DATEPART(YEAR, SAMPLE_DATE) = '2013' AND
DATEPART(MONTH,SAMPLE_DATE) = '01' AND
DATEPART(DAY, SAMPLE_DATE) = '01'
Is it usefull for you?
select * from table
where month(date)=month(getdate())-1
Edit
if you mean last month from today. or previous month from a specific date then you need to do something like this
SELECT DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
Or to get records from previous month of the year you can do something like this
SELECT * FROM Table
WHERE MONTH(Date) = DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
AND YEAR(Date) = DATEPART(YEAR, DATEADD(MONTH, -1, [Date])) --<-- or pass year for which year you are checking
To make your aquery SARGable (Suggested by t-clausen.dk)
select * from table
where date >=dateadd(m, datediff(m, 0, current_timestamp)-1, 0)
and date < dateadd(m, datediff(m, 0, current_timestamp)-1, 0)
Read here more about sargable Queries when working with date/datetime datatypes.
You can try to use the between statement to get the specific dates:
Select * from table where date between '01-01-2014' and '14-01-2014'

SQL get Monthly, and weekly data

I am writing a query to give me number of products sold this week, this month and this year (3 separate columns) on a week to date, month to date and year to date scale meaning today for example it will show products sold since monday, since the first of the month and since first of the year and this is to continue with each following week, month and year as time goes, there also are to be 3 other columns with the same logic for last year. What i need is help getting the date query using DATEADD or DATEDIFF (example (DATEADD(minute, -15, GETDATE())).
thank you very much and also i'm using SQL Server 2008
Here is some untested code which could probably be optimized, but should get you going in the right direction. This uses a PIVOT operation to transform your rows into columns.
SELECT WeekCount, MonthCount, YearCount
FROM
(
SELECT ProductId,
CASE
WHEN ProductSoldDate >= DATEADD(dd, 1 - DATEPART(dw, GETDATE()), GETDATE())
THEN 'WeekCount'
WHEN ProductSoldDate >= DATEADD(mm, DATEDIFF(mm,0,GETDATE()), 0)
THEN 'MonthCount'
WHEN ProductSoldDate >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
THEN 'YearCount'
END as lbl
FROM Products
) ProductSales
PIVOT
(
COUNT(ProductId)
FOR lbl IN ([WeekCount], [MonthCount], [YearCount])
) t
Here is the SQL Fiddle.
Good luck.
Using the DATEADD function
In some circumstances, you might want to add an interval of time to a DATETIME or SMALLDATETIME value or subtract an interval of time. For example, you might need to add or subtract a month from a specific date. You can use the DATEADD function to perform this calculation. The function takes the following syntax:
DATEADD(date/time_part, number, date)
Example:
SELECT OrderDate, DATEADD(mm, 3, OrderDate) AS NewDate
FROM Sales.Orders
WHERE OrderID = 1001
Using the DATEDIFF function
The DATEDIFF function calculates the time interval between two dates and returns an integer that represents the interval. The function takes the following syntax:
DATEDIFF(date/time_part, start_date, end_date)
Example:
SELECT OrderDate, DelivDate,
DATEDIFF(hh, OrderDate, DelivDate) AS HoursDiff
FROM Sales.Orders
WHERE OrderID = 1002

sql get count of month

In SQLExpress, I have a table that contains a datetime-column. It is formatted like this:
19.03.2012 00:00:00
Now, there are a lot of dates in there and I want to build a WPFChart, that shows me, how much dates are in march, in april and so on.
How can I manage this in sql that I get the count of one month?
Use:
select month(dateColumn), count(*)
from table
group by month(dateColumn)
You can extract the month of a date with Month() funciton.
than with a simple group by, you get the count for every month
To get only one month...
SELECT
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20120101'
AND dateColumn < '20120201'
To get multiple months, but grouped by month (and accounting for year).
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0),
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20110301'
AND dateColumn < '20120301'
GROUP BY
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0)