Averages from another table when combined

CREATE TABLE `reviews` (
  `id` int(11) NOT NULL,
  `average` decimal(11,2) NOT NULL,
  `house_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `reviews` (`id`, `average`, `house_id`) VALUES
(1, '10.00', 1),
(2, '10.00', 1);
ALTER TABLE `reviews`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `reviews`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

CREATE TABLE `dummy_reviews` (
  `id` int(11) NOT NULL,
  `average` decimal(11,2) NOT NULL,
  `house_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `dummy_reviews` (`id`, `average`, `house_id`) VALUES
(0, '2.00', 1);
ALTER TABLE `dummy_reviews`
  ADD PRIMARY KEY (`id`);

      

And request

SELECT
  AVG(r.average) AS avg1,
  AVG(dr.average) AS avg2
FROM
  reviews r
LEFT JOIN
  dummy_reviews dr ON r.house_id = dr.house_id

      

result

avg1        avg2    
10.000000   2.000000

      

All is well by now, but (10 + 2) / 2 = 6 ... wrong result

I need (10 + 10 + 2) / 3 = 7.33 ... How can I get this result?

SQLFiddle

+3


source to share


2 answers


You have the values ​​concatenated and as such you won't have 3 rows, you will have 2. What you need is a concatenation so that you can have all the rows from your middle tables and do calculations from it. Like this:

select avg(average) from
  (select average from reviews
   union all
   select average from dummy_reviews
  ) queries

      



See it here: http://sqlfiddle.com/#!9/e0b75f/3

+3


source


Jorge's answer is the simplest approach (and I have duly supported it). In response to your comment, you can do the following:

select ( (coalesce(r.suma, 0) + coalesce(d.suma, 0)) /
         (coalesce(r.cnt, 0) + coalesce(d.cnt, 0))
       ) as overall_average
from (select sum(average) as suma, count(*) as cnt
      from reviews
     ) r cross join
     (select sum(average) as suma, count(*) as cnt
      from dummy_reviews
     ) d;

      



Actually, I am suggesting this not only because of your comment. This may be the best code in some cases.

+3


source







All Articles