简体   繁体   English

如何计算特定天内的行数

[英]How to count the numbers of rows within a certain days

I would like to perform a query that counts the number of rows that have a close date within 60 days of open_date by store. 我想执行一个查询,该查询按商店对open_date的60天内具有截止日期的行数进行计数。

Sample: Table A 样品:表A

Store  Open Date  Close Date
A      2017-01-01   2017-01-31
B      2017-02-02   Null
A      2017-01-02   2018-01-21

Thanks in advance. 提前致谢。

使用datediff()

SELECT count(*) FROM [Table A] WHERE datediff(Close_date,Open_date) <= 60;

Try this on of the queries below: 尝试以下查询:

SELECT count(*) numberOfDays
FROM TableA
WHERE close_date>=CURRENT_DATE - INTERVAL 60 DAY;

SELECT count(*) numberOfDays
FROM TableA
WHERE close_date>=CURRENT_DATE - INTERVAL '60' DAY;

See it work on SQL Fiddle . 看到它在SQL Fiddle上工作

select store, open_date, count(*)
from tableA
where close_date between date_sub(open_date, interval 60 DAY) and date_add(open_date, interval 60 DAY)
group by store, open_date;

This will work but your starting date has to either be current date or the open_date (which is what your question was). 这将起作用,但是您的开始日期必须是当前日期或open_date(这是您的问题)。 Given that the open_date appears to be different for each row, your count is going to be ... interesting. 鉴于每一行的open_date似乎都不同,因此您的计数将会很有趣。

Also, count will always return something, so unless you use an if or case statement keying on 0 (zero) it will return a 0 not a null. 同样,count将始终返回某些内容,因此除非您使用键为0(零)的if或case语句,否则它将返回0而不是null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM