K
K
Konstantin2015-12-25 21:41:49
MySQL
Konstantin, 2015-12-25 21:41:49

How to make a query in mysql that has count?

Hello. There are two tables managers and orders
Table structure manager

CREATE TABLE `manager` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(32) CHARACTER SET latin1 NOT NULL,
  `last_name` VARCHAR(32) CHARACTER SET latin1 NOT NULL,
  `email` VARCHAR(32) CHARACTER SET latin1 NOT NULL,
  `chief_id` INT(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `chief_id` (`chief_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

Claim table structure
CREATE TABLE `claim` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `manager_id` INT(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `sum` FLOAT NOT NULL,
  PRIMARY KEY (`id`),
  KEY `manager_id` (`manager_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;

Foreign key constraints on the claim table
ALTER TABLE `claim`
  ADD CONSTRAINT `claim_ibfk_1` FOREIGN KEY (`manager_id`) 
  REFERENCES `manager` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

Foreign key constraints on the manager table
ALTER TABLE `manager`
  ADD CONSTRAINT `manager_ibfk_1` FOREIGN KEY (`chief_id`) 
  REFERENCES `manager` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

Please help to choose managers who have more orders than their leader. I can't choose. The closest option is
SELECT a.first_name, b.first_name, COUNT( a.first_name ) , COUNT( b.first_name ) 
FROM manager a, manager b,  `claim` 
WHERE a.id = b.chief_id AND a.id = claim.manager_id 
GROUP BY a.first_name

But where to shove the condition where count of one > count of the other, I'll never know. If I put in WHERE
AND COUNT( a.first_name ) > COUNT( b.first_name )
I get an error Invalid use of group function if I put it in having
SELECT a.first_name, b.first_name, COUNT( a.first_name ), COUNT( b.first_name )
 FROM manager a, manager b, claim WHERE a.id = b.chief_id 
AND a.id = claim.manager_id GROUP BY a.first_name 
HAVING COUNT( a.first_name ) > COUNT( b.first_name )

then the answer is empty.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2015-12-25
@kostik34

select mngrs.manager_id from
(select mn.chief_id, cl.manager_id, count(1) cn
  from claim cl
inner join manager mn on (mn.id = cl.manager_id) and (mn.chief_id is not null)
group by mn.chief_id, cl.manager_id) mngrs
inner join 
(select cl.manager_id chiefid, count(1) cn
  from claim cl
inner join manager mn on (mn.id = cl.manager_id) and (mn.chief_id is null)
group by cl.manager_id) chiefs on chiefs.chiefid = mngrs.chief_id
where mngrs.cn > chiefs.cn

Didn't check the request, but the idea should be roughly understandable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question