sql - 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
推荐阅读
- kubernetes - PromQL - 命令在 pod 上运行时发出警报
- python - tensorflow 2 从顺序到功能
- node.js - 我想将电话号码用作静态而不是由 socket.io lib 生成的动态套接字 ID
- python - 该非线性系统的相图
- jmeter - 如何使用 Jmeter 在循环中运行 2 个线程组?
- vba - 如何修复 Form.Recordset 中的“无当前记录”-错误?
- arrays - for ... in 循环是否遍历序列的副本?
- php - Sylius - Shop Api - 当 shop API 运行时发生错误找不到模板“”
- python - 将存储在元组中的坐标字符串转换为列表
- azure - 用于监视 Azure VM 的逻辑应用程序未发送预期的电子邮件