Answer the question
In order to leave comments, you need to log in
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 ;
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 ;
ALTER TABLE `claim`
ADD CONSTRAINT `claim_ibfk_1` FOREIGN KEY (`manager_id`)
REFERENCES `manager` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `manager`
ADD CONSTRAINT `manager_ibfk_1` FOREIGN KEY (`chief_id`)
REFERENCES `manager` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
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
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 )
Answer the question
In order to leave comments, you need to log in
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 find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question