bcmcfc
bcmcfc

Reputation: 26795

Combine two MySQL queries looking at separate tables to count side by side

I have two MySQL queries which count the number of records grouped by day. The content relates to each other (I eventually want to see one count as a percentage of the other). How do I go about grouping them together?

1:

SELECT 
    COUNT(*) AS `total`, 
    CONCAT(DAY(logtime),'.',MONTH(logtime),'.',YEAR(logtime)) AS `day`
FROM log 
WHERE some-conditions-here
GROUP BY
    YEAR(logtime), MONTH(logtime), DAY(logtime)

2:

SELECT 
    COUNT(*) AS `otherTotal`,
    CONCAT(DAY(tstamp),'.',MONTH(tstamp),'.',YEAR(tstamp)) AS `day`
FROM othertable
GROUP BY
    YEAR(tstamp), MONTH(tstamp), DAY(tstamp)

Upvotes: 1

Views: 217

Answers (1)

ajreal
ajreal

Reputation: 47321

select
  q1.day,
  (q2.total / q1.total)*100 as percentage
from 
(
  // first group by
) as q1
inner join
(
  // second group by
) as q2
using day;

With this, q1 is always non-zero,
so, you don't get any division by zero (hopefully, have fun!)

Upvotes: 2

Related Questions