I’m trying to extract from a table the value that appears the maximum number of times for each distinct value of a different field. For example, if the data set was:
a x
a x
a y
b x
b y
c x
c y
c y
the query would yield
a x 2
b x 1
c y 2
My experiments use the following:
CREATE TABLE IF NOT EXISTS `maxcount` (
`what` varchar(1) DEFAULT NULL,
`loc` varchar(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and
INSERT INTO `maxcount` (`what`, `loc`) VALUES
('a', 'x'),
('a', 'x'),
('a', 'y'),
('b', 'x'),
('b', 'y'),
('c', 'x'),
('c', 'y'),
('c', 'y');
The first part is easy:
select what, loc, count(loc) howmany from maxcount group by what, loc;
What I haven’t yet figured out is how to use this to get one row for each “what” showing the value of loc that has the maximum count and value of the maximum.
The solution is NOT:
select what, loc, max(howmany) from (
select what, loc, count(loc) howmany from maxcount group by what, loc)
A group by what;
Because it yields:
a x 2
b x 1
c x 2
Your guidance gratefully accepted!
George
Check this out… in order to avoid referencing the same group of results, I created a table… you should delete it after doing the processing, or replace maxcounttemp with
(SELECT what, loc, count(loc) howmany FROM maxcount GROUP BY what, loc) as tblXI tried to make it TEMPORARY, but you can’t use it inside a subquery if the outer table is the same one.hope it helps… keep in mind that bx or by are equally possible on this query…