我有两张桌子:
带字段的doctorreport:
医生
代表姓名
医生姓名
添加日期
有字段的医院:
住院
代表姓名
医院名称
医生姓名
添加日期
我需要用添加的日期统计医生报告和医院中每个RepName添加的记录。
我需要它看起来像这样:

RepName | DoctorReportsCount | HospitalsReportsCount | DateAdded
        |                    |                       |
  John  |          15        |          12           | 9/4/2012

doctorsreports表中的RepName等于hospitals表中的RepName。
@bluefeet这部分是我需要的,但是如果RepName在这个日期中没有添加任何记录,那么date added=0是否可以统一DateAdded字段。例如:
RepName | DoctorReportsCount | HospitalsReportsCount | DateAdded
        |                    |                       |
  John  |          15        |          12           | 9/4/2012
  Ann   |          9         |           0           | 9/2/2012
Tamer   |          0         |           12          | 9/1/2012

最佳答案

听起来你想这么做:
select d.RepName, count(d.RepName) DoctorReportsCount, count(h.RepName) HospitalsReportsCount, d.DateAdded from doctorreports d inner join hospitals h on d.RepName = h.RepName group by d.RepName, d.DateAdded
编辑:
select * from ( select d.RepName, count(d.RepName) DoctorReportsCount , d.dateadded from doctorreports d group by d.RepName, d.dateadded ) d left join ( select h.RepName, count(h.RepName) HospitalsReportsCount , h.dateadded hDateadded from hospitals h group by h.RepName, h.dateadded )h on d.RepName = h.RepNamesee SQL Fiddle with demo
编辑#2,如果您想返回丢失天数的数据,那么我建议您创建一个包含日历日期的表,然后您可以返回丢失天数的数据。下面应该返回您正在寻找的内容。请注意,我为此查询创建了一个日历表:

select COALESCE(d.drep, '') repname,
  COALESCE(d.DCount, 0) DoctorReportsCount,
  COALESCE(h.HCount, 0) HospitalsReportsCount,
  c.dt Dateadded
from calendar c
left join
(
  select repname drep,
    count(repname) DCount,
    dateadded ddate
  from doctorreports
  group by repname, dateadded
) d
  on c.dt = d.ddate
left join
(
  select repname hrep,
    count(repname) HCount,
    dateadded hdate
  from hospitals
  group by repname, dateadded
) h
  on c.dt = h.hdate
  and d.drep = h.hrep

SQL Fiddle with Demo
如果您不关心其他日期,那么这就是您在没有date表的情况下的做法:
select COALESCE(d.RepName, '') repname,
  COALESCE(d.DoctorReportsCount, 0) DoctorReportsCount,
  COALESCE(h.HospitalsReportsCount, 0) HospitalsReportsCount,
  COALESCE(p.PharmacyReportsCount, 0) PharmacyReportsCount,
  d.dateadded Dateadded
from
(
  select d.RepName,
      count(d.RepName) DoctorReportsCount
    , d.dateadded
  from doctorreports d
  group by d.RepName, d.dateadded
) d
left join
(
  select h.RepName,
    count(h.RepName) HospitalsReportsCount
  , h.dateadded hDateadded
  from hospitals h
  group by h.RepName, h.dateadded
)h
  on d.RepName = h.RepName
  and d.dateadded = h.hDateadded
left join
(
  select p.RepName,
    count(p.RepName) PharmacyReportsCount
  , p.dateadded hDateadded
  from PharmacyReports p
  group by p.RepName, p.dateadded
)p
  on d.RepName = p.RepName
  and d.dateadded = p.hDateadded

SQL Fiddle with Demo

关于mysql - 计算来自两个表的记录,这些表按一个字段分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12429347/

10-10 10:56