I have table like this:
idjob category customer 1560 001 1 1560 0010 1 1560 002 1 1562 001 2 1562 0010 2 1563 001 2 1563 002 3 1563 0010 3 1563 004 3
One customer can have more idjobs. Every single jobs contain a group of categories.
I would like to select the number of customer that have two or more specifics category by its jobs.
Probably it is a simple query.
How can i do that? Thank you
You could count the number of different idjob
per customer:
SELECT customer, GROUP_CONCAT(idjob) AS jobs
FROM mytable
GROUP BY customer
HAVING COUNT(DISTINCT idjob) > 1
You can get the customers meeting the condition using:
select customer
from t
group by customer
having min(category) <> max(category);
To get the number, use a subquery:
select count(*)
from (select customer
from t
group by customer
having min(category) <> max(category)
) c;
Note that "2" is a special case. It can be handled by comparing the max()
and min()
. The more general solution would use count(distinct category) >= 2
. However, count(distinct)
is more resource intensive than simpler aggregation functions.
EDIT:
Perhaps I misread the original question.
If you want customers with a particular set of categories, you can still use GROUP BY
and HAVING
:
select customer
from t
where category in (. . .)
group by customer
having count(*) = <n>;
Here . . .
. . .
is the list of categories you want. <n>
is the number of categories in that list.
If you can have duplicate customer
/ category
pairs, then use this having
:
having count(distinct category) = <n>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.