"Practical SQL function Group_conca" I know you want to use GROUP_CONCAT with count, like the number of people in different combinations?

Source: Internet
Author: User

Background

A few days ago to review the MySQL function, know that a group_concat function is very useful, but has not actually used. Today, I had a problem and asked me to be a prick. Suppose there is a purchase Product Delta table order_list.

ALTER TABLE pet drop column User2_id;insert into pet (User_id,pet_id,id) VALUES (2, ' a ', 1), (3, ' B ', 1), (4, ' C ', 2), (5, ' a ', 2), (6, ' A ', 3), (7, ' B ', 2), (8, ' C ', 2), (9, ' D ', 1);

/*

Inquire about all products purchased by each user_id (de-weight)

Select O. user_id , Group_concat (Distinct o. product_id ORDER by O. product_id ASC SEPARATOR ') from Order_list o
GROUP by O.user_id

Description: 1.group_concat in the distinct is not necessary, not just do not go heavy; 2. ORDER by O. product_idASC is not required, the default is the merged part is in ascending order, want to in descending order can use desc;3. SEPARATOR ' is also not required and is separated by commas by default. For example:

SELECT o. user_id , Group_concat (o. product_id ) From Order_list o
GROUP by O.user_id
*/

/*

Find out how many different product combinations have multiple products at the same time.

Select T.product_group,count (t.user_id) from
(Select O. user_id , Group_concat (Distinct o. product_id ORDER by O. product_id ASC SEPARATOR ') ' Product_group ' from Order_list o
GROUP by O.user_id
) T
GROUP BY T.product_group

*/

Query A/b/c/d/ab/ac/ad/bc/bd/cd/abc .... How many people are there in a 4+6+4+1=15 combination?

Select O. product_id , COUNT (distinct o.id) from Order_list o
GROUP by O.product_id
Union
Select from

"Practical SQL function Group_conca" I know you want to use GROUP_CONCAT with count, like the number of people in different combinations?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.