Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

MySQL - how to count rows within date range while grouping by date

I have to count amount of employee_id's whose row apply to the rule: date>=valid_from and date<valid_to in the table in given time, grouping by date and company_id. Fiddle with example:

http://sqlfiddle.com/#!9/994b8d/1

so the expected outcome would be for example:

company_id, date,       employees
1           2019-01-01  1
1           2020-01-01  1
1           2021-01-01  0
2           2020-01-01  3
2           2020-02-01  3
2           2020-03-01  2
2           2020-04-01  1
2           2020-05-01  0

I found quite similar question: MySQL: Grouping by date ranges but I would need some variable that could be larger or smaller than valid_to and valid_from. Plus I don't want to divide the year into periods except the date itself.

It can be done only with regard to dates when it changes, or going through all dates, though it would be much better if it was done along dates with changes to minimise the number of rows. I'm using MySql 8 and newer. Is there some special built in function for such operations? If not, how to do it in reasonable way?

question from:https://stackoverflow.com/questions/66065017/mysql-how-to-count-rows-within-date-range-while-grouping-by-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...