以下是一个示例的SQL查询,展示了如何按组对多个表进行聚合:
SELECT c.category_name, COUNT(p.product_id) as product_count, SUM(p.product_price) as total_price
FROM categories c
JOIN products p ON c.category_id = p.category_id
GROUP BY c.category_name;
在这个示例中,我们有两个表:categories
和products
。我们想要按照类别对产品进行聚合,以获取每个类别的产品数量和总价格。
在查询中,我们使用了JOIN
操作将categories
表和products
表连接起来,连接条件是它们的category_id
相等。然后,我们使用GROUP BY
子句将结果按照category_name
分组。
在SELECT
子句中,我们选择了需要展示的列:category_name
、COUNT(p.product_id)
和SUM(p.product_price)
。COUNT
函数用于计算每个类别的产品数量,SUM
函数用于计算每个类别的产品总价格。
最后,我们得到了按组进行聚合的结果,其中包含每个类别的产品数量和总价格。
上一篇:按组对定性变量进行排序并保留索引