我试图找出在任何给定的时间有多少用户在一栋楼里。为此我有两张桌子,
表a

Name    ENTER                  EXIT                       COMPANY    Employee
Jack    2013-01-01 01:00:00    2013-01-01 02:00:00        trilogy    Security Guard
Jane    2013-01-01 02:00:00    2013-01-01 03:00:00        trilogy    Security Guard
Judy    2013-01-03 01:00:00    2013-01-04 02:00:00        sindicate  Cleaner
Sam     2013-01-02 05:00:00    2013-01-02 08:00:00        lyop       Engineer

为了找出我在另一张桌子里有多少人,
表n
a   b
1   2013-01-01 01:00:00
2   2013-01-01 02:00:00
3   2013-01-01 03:00:00
-
-
x   2013-01-05 23:00:00

然后我将它们结合在一起,使用
  SELECT DATE(n.b), HOUR(n.b), COUNT(*)
  FROM
  a INNER JOIN n ON n.b BETWEEN a.ENTER
  AND a.EXIT
  GROUP BY 1, 2

结果=
Date(n.b)    Hour(n.b)    Count(*)
2013-01-01   1            1
2013-01-01   2            2
2013-01-01   3            1
---
---
2013-01-02   5            1
so on....

这是我想要的。不过,现在我想能够告诉顶级公司(不分员工类型)和顶级员工(不分公司)类型的建筑每小时的职业,除了上面的结果。
例如
 Date         Hour  Count(*)     Top-Company  Comp-Count   Top-Employe      Emp-Count
 2013-01-01   01    1              Trilogy      1          Security Guard    1
 2013-01-01   02    2              Trilogy      2          Security Guard    2

如果可能的话,我想把它加入到我现有的查询中。我对MySQL知之甚少。

最佳答案

做这种事情的一般方法是从简单的关系中建立所需的复杂关系。您可以将查询视为一个表,然后再次将其分组,或者将其连接到一个表或另一个查询。我们先做公司。
这将获得每个日期+时间内每个公司的员工数:

select date(n.b) end_date, hour(n.b) end_hour, a.company, count(*) employees_present
from n, a
where n.b between a.enter and a.exit
group by 1, 2, 3;

这将使您获得任何一家公司在每个日期+时间内拥有的最大数量的员工(但会因以下原因在组中丢失公司名称):
select end_date, end_hour, max(employees_present) max_employees_present
from (
  select date(n.b) end_date, hour(n.b) end_hour, a.company, count(*) employees_present
  from n, a
  where n.b between a.enter and a.exit
  group by 1, 2, 3
) company_counts
group by 1, 2;

加入他们,找回公司的名字:
select company_counts.end_date, company_counts.end_hour, company_counts.company
from
(
  select date(n.b) end_date, hour(n.b) end_hour, a.company, count(*) employees_present
  from n, a
  where n.b between a.enter and a.exit
  group by 1, 2, 3
) company_counts,
(
  select end_date, end_hour, max(employees_present) max_employees_present
  from (
    select date(n.b) end_date, hour(n.b) end_hour, a.company, count(*) employees_present
    from n, a
    where n.b between a.enter and a.exit
    group by 1, 2, 3
  ) company_counts_2
  group by 1, 2
) max_company_counts
where company_counts.end_date = max_company_counts.end_date and
  company_counts.end_hour = max_company_counts.end_hour and
  company_counts.employees_present = max_company_counts.max_employees_present;

在你完成上述工作之后,你应该能够
将整个内容加入到原始查询中(在每个日期+时间中都有总数),然后
对于员工类型,请再次执行此操作。

08-25 12:34