[英]Count register depending of current date
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? 我想知道如何仅
COUNT
等于当前月份和年份的日期寄存器,例如,在这种情况下,如果在03个月中只有一个寄存器,我只能计数1,该如何实现呢? 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. 我们可以将表中的创建日期和当前日期都转换为
yyyy-mm
字符串,然后检查它们是否相等。
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
. 尽管这看起来比其他解决方案更复杂,但是所有复杂性都在
getdate()
-这意味着优化程序可以在creationdate
上使用索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.