在 SQL 中计数和加入 (oracle)
Counting and Joining in SQL (oracle)
我的数据库包含 2 个 table 称为产品和 product_categories。
Product_categories 包含 category_id 和 category_name
产品包含 category_id 和其他与此问题无关的信息。
我需要计算产品 table 中使用 category_id 的产品数量,并显示它们在 product_categories table.[=17 中的名称=]
Select * FROM product_categories
显示:
category_id, category_name
1 CPU
2 Video Card
3 RAM
4 Mother Board
5 Storage
和
Select * FROM products
显示(浓缩):
category_id
399.77 564.89 1
481.56 554.99 1
4058.99 5499.99 2
3619.14 4139 2
2505.04 3254.99 2
... UPTO CATEGORY_ID 5
当前报表:
SELECT category_id , COUNT (1) AS "TOTAL"
FROM products
GROUP BY category_id;
输出:
Category_id, total
1 70
2 50
5 108
4 60
期望的结果:我需要显示类别 ID,然后是类别名称,最后是产品总数。
加入那些 tables:
select p.category_id,
c.category_name,
count(*) as total
from products p join product_categories c on c.category_id = p.category_id
group by p.category_id,
c.category_name
如果要显示 products
table.
中不存在的类别,您可能需要将其转为外部联接
我的数据库包含 2 个 table 称为产品和 product_categories。
Product_categories 包含 category_id 和 category_name 产品包含 category_id 和其他与此问题无关的信息。
我需要计算产品 table 中使用 category_id 的产品数量,并显示它们在 product_categories table.[=17 中的名称=]
Select * FROM product_categories
显示:
category_id, category_name
1 CPU
2 Video Card
3 RAM
4 Mother Board
5 Storage
和
Select * FROM products
显示(浓缩):
category_id
399.77 564.89 1
481.56 554.99 1
4058.99 5499.99 2
3619.14 4139 2
2505.04 3254.99 2
... UPTO CATEGORY_ID 5
当前报表:
SELECT category_id , COUNT (1) AS "TOTAL"
FROM products
GROUP BY category_id;
输出:
Category_id, total
1 70
2 50
5 108
4 60
期望的结果:我需要显示类别 ID,然后是类别名称,最后是产品总数。
加入那些 tables:
select p.category_id,
c.category_name,
count(*) as total
from products p join product_categories c on c.category_id = p.category_id
group by p.category_id,
c.category_name
如果要显示 products
table.