Answer the question
In order to leave comments, you need to log in
Help compose 2 SQL queries
There is a table with three columns:
Company - Customer - Product
Conditions:
- one customer can be associated with only one company
- A customer can have several products
- A company can have several customers
- association of companies with products is not considered
Accordingly, the records look something like this:
company_1 | customer_1 | item_1
company_1 | customer_1 | item_2
company_1 | customer_1 | item_3
company_1 | customer_2 | item_2
company_2 | customer_3 | item_1
company_2 | customer_4 | item_3
company_2 | customer_3 | item_2
Task:
1. to build the TOP-100 companies by the number of buyers who bought more than 10 different products. Records in the table to the fig.
2. having this or that value of the company, find out its place in this rating
Answer the question
In order to leave comments, you need to log in
SELECT `company` , customer, COUNT( `item` ) AS items
FROM `test`
GROUP BY company
HAVING COUNT( `item` ) >10
ORDER BY COUNT( `customer` ) DESC
-- checked on 4M rows
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`company` int(11) NOT NULL,
`customer` int(11) NOT NULL,
`item` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `search` (`company`,`customer`,`item`)
) ENGINE=MyISAM AUTO_INCREMENT=4000001 DEFAULT CHARSET=utf8;
-- 1) ~ 2.2sec
SELECT company, count(customer) as `customers_count`
FROM (SELECT customer, company FROM test GROUP BY customer HAVING COUNT(DISTINCT item) > 5) as `temp`
GROUP BY company
ORDER BY customers_count DESC
LIMIT 100
-- 2) ~2.2sec
SET @rank = 0;
SELECT rank, company FROM (
SELECT @rank := @rank + 1 as `rank`, company FROM (
SELECT company, count(customer) as `customers_count`
FROM (SELECT customer, company FROM test GROUP BY customer HAVING COUNT(DISTINCT item) > 5) as `temp`
GROUP BY company
ORDER BY customers_count DESC
LIMIT 100
) as `temp2`
) as `temp3`
WHERE company = 159
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question