简体   繁体   English

如何计算小时之间的total_number-MySQL

[英]how to count the total_number in between hour's - MySQL

I have a Mysql table like 我有一个Mysql表

|Doctor_id | login_hour | logout_hour |
-------   -----------  -----------
 12         10          12
 13         11          13
 14         09          13
 15         13          14

I want to know how many doctors is schedule for every hour. 我想知道每小时安排多少医生。 If the doctor has schedule between 11 and 13, he should appear in 11th & 12th hour.Kindly let me know how to do this in MySQL 如果医生的时间表在11到13之间,那么他应该在11和12个小时出现。请让我知道如何在MySQL中执行此操作

The output should be like 输出应该像

Hour | Number_of_doctors
----   -----------------
10         2
11         3
12         2
13         1

You can do with inner SELECT , eg: 您可以使用内部SELECT ,例如:

SELECT DISTINCT t.login_hour,
(SELECT COUNT(*) FROM doctors WHERE login_hour <= t.login_hour AND logout_hour 
> t.login_hour) AS number_of_doctors
FROM doctors t
ORDER BY t.login_hour;

Here's the SQL Fiddle . 这是SQL Fiddle

Update 更新

This would assume at least one doctor is logged in (as Strawberry has rightly said). 这将假定至少有一位医生已登录(正如Strawberry正确地说的那样)。 If you want the total number of doctors logged in at any given hour then you can use the below query: 如果您希望在任何给定时间登录的医生总数,则可以使用以下查询:

SELECT COUNT(*) 
FROM doctors WHERE login_hour <= ? AND logout_hour > ?;

Here's one idea - but as stated in comments, I'd actually handle the bulk of this in application code... 这是一个主意-但正如注释中所述,我实际上将在应用程序代码中处理大部分问题...

SELECT x.hour
     , COUNT(*) total
  FROM
     ( SELECT  9 hour UNION 
       SELECT 10 UNION
       SELECT 11 UNION
       SELECT 12 UNION
       SELECT 13 UNION
       SELECT 14 
     ) x
  JOIN my_table y
    ON x.hour >= y.login_hour 
   AND x.hour < y.logout_hour
 GROUP
    BY hour;

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

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