Mysql
 sql >> Database >  >> RDS >> Mysql

Conta i record di due tabelle raggruppate per un campo

Sembra che tu stia cercando di farlo:

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

modifica:

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.RepName

vedi SQL Fiddle con demo

modifica n. 2, se desideri restituire i dati per i giorni mancanti, ti consiglierei di creare una tabella per contenere le date del calendario, quindi puoi restituire i dati per i giorni mancanti. Quanto segue dovrebbe restituire ciò che stai cercando. Tieni presente che ho creato una tabella del calendario per questa query:

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

vedi SQL Fiddle con demo

Se non ti interessano le altre date, allora è così che lo faresti senza una date tabella:

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

vedi SQL Fiddle con demo