简体   繁体   中英

Get "group by" parameter column name/ alias from another table

I have a table podcast . Each podcast has category and subcategory associated to it in the form of ids.

在此处输入图片说明

This category_id and subcategory_id have their name values in their respective tables -

在此处输入图片说明 在此处输入图片说明

Now, I want to get the count of podcasts under each category, subcategory combination -

SELECT podcast_category_id, podcast_subcategory_id, count(*)
FROM podcasts
where podcast_owner = 14 AND podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY podcast_category_id, podcast_subcategory_id

Output -

在此处输入图片说明

The output shows podcast_category_id and podcast_subcategory_id columns as expected. However, I want to replace podcast_category_id with category_name and podcast_subcategory_id with sub_category_name . How do I do that?

Join to those tables.

    SELECT c.category_name, sc.sub_category_name, count(p.*)
    FROM podcasts p
    join categories c
      on c.category_id = p.podcast_category_id
    join sub_categories sc
      on sc.sub_category_id = p.podcast_subcategory_id
    where p.podcast_owner = 14 
      AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
    GROUP BY 1,2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM