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
603 views
in Technique[技术] by (71.8m points)

mysql - Query Count for each year based on single date

I am being asked to provide some reporting on Starter/Leavers based on information we are already collecting.

I am trying to figure out whether this can be done by the MySQL itself, or if I will need to make multiple calls.

At the simplest level our data structure is:

ID    psName     dtStart     dtLeave

(This is produced from multiple tables that pull in Office, Status, etc, which we might use for more complicated queries)

For a given date I can use the following Query to get the number of people in the company:

SELECT COUNT(*) FROM
(
  SELECT ID, psName, dtStart, dtLeave
  FROM people
) st
WHERE (dtStart <= "2016-06-04" ) 
AND (dtLeave >= "2016-06-04" OR dtLeave IS NULL) 

I would like to be able to feed in a date, for example "2016-04-06" and get a list list of counts (either as columns or rows) for that date historically i.e.

6/4/2016 200
6/4/2015 175
6/4/2014 150
6/4/2014 125
6/4/2013 100

Does this make sense, and if so, is it possible?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Notice that there is no start and end date, this query will scan all table records.

In fact, you can reduce your query to:

SELECT YEAR(dtStart) as 'year', COUNT(*) FROM
FROM people
WHERE MONTH(dStart) = 4 AND DAY(dStart) = 6
GROUP BY YEAR(dtStart);

UPDATE

To get people employed on the selected period:

SET @SelectedDate = '2016-04-06';

SELECT YEAR(dStart), COUNT(*), @SelectedDate FROM
(
  SELECT ID, psName, dtStart, dtLeave
  FROM people
  WHERE DATE_FORMAT(dtStart, '%m%d') <= DATE_FORMAT(@SelectedDate, '%m%d')
        AND DATE_FORMAT(dtleave, '%m%d') >= DATE_FORMAT(@SelectedDate, '%m%d')
) st
GROUP BY YEAR(dStart);

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

...