Link to home
Start Free TrialLog in
Avatar of altariamx2003
altariamx2003Flag for Mexico

asked on

merge two tables with a column in comun

I have two tables

table inscripcion
------------------------------------------------------
|date         |   other fields  |
------------------------------------------------------


table visitas
------------------------------------------------------
|date         |   other fields  |
------------------------------------------------------

When I need the total of records of this tables group by date I use this querys:
SELECT date, COUNT( * ) AS total_inscripcion
FROM inscripcion
GROUP BY date

Open in new window


SELECT date, COUNT( * ) AS total_visitas
FROM visitas
GROUP BY date

Open in new window


I would like to make this querys in a single query where I receive something like this:
------------------------------------------------------------------
|date         |   total_inscripcion  |   total_visitas  |
------------------------------------------------------------------
Where date is the merge between the fields date from inscripcion and date from visitas
           total_inscripcion: total of records from inscripcion group by date
           total_visitas: total of records from visitas group by date.

I try this one:
SELECT DISTINCT t1.date, t1.total_inscripcion, t2.total_visitas
FROM (SELECT date, count( * ) AS total_inscripcion FROM inscripcion GROUP BY date)t1
LEFT JOIN (SELECT date, count( * ) AS total_visitas FROM visitas GROUP BY date)t2 ON t1.fecha = t2.date
UNION SELECT DISTINCT t2.date, t1.total_inscripcion, t2.total_visitas
FROM (SELECT date, count( * ) AS total_inscripcion FROM inscripcion GROUP BY date)t1
RIGHT JOIN (SELECT date, count( * ) AS total_visitas FROM visitas GROUP BY date)t2 ON t1.date = t2.date

Open in new window


I works, but I would like to know if somebody knows if there is a better options to do this query.


best regards
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Try this

SELECT i.date, COUNT(*) AS InscripcionTotal, b.VisitasTotal 
  FROM inscripcion i
  LEFT JOIN (SELECT date AS VisitasDate, COUNT(*) AS VisitasTotal FROM visitas GROUP BY date) b
    ON i.date = b.VisitasDate
  GROUP by i.date

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I would go with Paul's solution
Avatar of altariamx2003

ASKER

thanks for take time to answer me

I appreciate it