0

I am trying to write a query that can get result from multiple tables:

Item Category

ic_id ic_name
1 PC
2 Laptop
3 Printer
4 Scanner

Items

i_id i_category i_name
1 1 Dell Optiplex
2 2 HP Probook 450
3 2 HP Probook650
4 3 HP Laserjet 402dn
5 1 Dell MT3030

Item Sale

is_id is_date is_customer
1 15-03-2021 John
2 16-03-2022 Jimmy
3 18-03-2023 Mark

Item Sale Detail

isd_id isd_sale_id isd_item
1 1 2
2 1 3
3 2 4
4 3 1
5 3 5
6 3 4

Is it possible to get combined result of GROUP CONCAT with COUNT in 1 query? Please guide me to write the query to get the desired result, I want the query result as shown below, Thanks:

Desired Result

is_id is_date is_customer items
1 15-03-2021 John Laptop: 3
2 16-03-2022 Jimmy Printer: 1
3 18-03-2023 Mark PC:2 , Printer: 1
0

1 Answer 1

2

If I understand correctly, this is just join but with two levels of aggregation:

select its.*, ic.categories
from item_sale its join
     (select isd.isd_sale_id,
             group_concat(ic_name, ':', cnt order by cnt desc) as categories
      from (select isd.isd_sale_id, ic.ic_name, count(*) as cnt
            from item_sale_detail isd join
                 items i
                 on isd.isd_item = i.i_id join
                 item_category ic
                 on i.i_category = ic.ic_id
            group by isd.isd_sale_id, ic.ic_name
           ) ic
      group by isd.isd_sale_id
     ) ic
     on i.is_id = ic.isd_sale_id;
 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.