I have a table who have creation date like:
SELECT [CreationDate] FROM Store.Order
So each register have one datetime like:
2018-03-14 00:00:00.000
2017-04-14 00:00:00.000
2017-06-14 00:00:00.000
I want to know how to COUNT
only register of Date equals to current month and year, for example in this case,if I only have one register in month 03 I just get 1 on count, how can I achieve it? Regards
Here is one option:
SELECT COUNT(*)
FROM Store.Order
WHERE
CONVERT(varchar(7), [CreationDate], 126) = CONVERT(varchar(7), GETDATE(), 126);
We can convert both the creation date in your table and the current date into yyyy-mm
strings, and then check if they be equal.
The most efficient way is to do:
where creationdate >= dateadd(day, 1 - day(getdate(), cast(getdate() as date)) and
creationdate < dateadd(month, 1, dateadd(day, 1 - day(getdate(), cast(getdate() as date)))
Although this looks more complex than other solutions, all the complexity is on getdate()
-- meaning that the optimizer can use indexes on creationdate
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.