我有四张桌子。 类别,产品,销售和评论。类别具有一个或多个产品,产品具有一个或多个评论,并且产品具有一个或多个销售。 现在我需要知道每个类别有多少产品,每个类别的平均得分以及每个类别的销售总额 我知道如何让他们:
按类别划分的销售额
SELECT category.name, COUNT(sale.id_product) as sale
FROM product
LEFT OUTER JOIN category on category.id_category=product.id_category
LEFT OUTER JOIN sale on sale.id_product =product.id_product
Group by category.name
按类别划分的平均分数
SELECT category.name, round(CAST(AVG(review.score as numeric),2)
FROM product
LEFT OUTER JOIN review on review.id_product = product.id_product
LEFT OUTER JOIN category on category.id_category=product.id_category
GROUP BY category.name
按类别分类的评论
SELECT category.name, COUNT(review.id_product)
FROM category
LEFT OUTER JOIN product on category.id_category = product.id_category
Left outer join review on product.id_product = review.id_product
Group by category.name
现在我希望他们中的三个在同一个查询中,它不起作用 我尝试过:
SELECT category.name as category,
COUNT(sale.id_product) as sales,
round(CAST(AVG(review.score as numeric),2) as average,
COUNT(review.id_product) as totalreviews
FROM product
FULL OUTER JOIN category on category.id_category = product.id_category
FULL OUTER JOIN sale on product.id_product=sale.id_product
FULL OUTER JOIN review on product.id_product = review.id_product
GROUP BY category.name
实施例
分类
+---------------+-----+
| category | id |
+---------------+-----+
| category1 | 1 |
| category2 | 2 |
+---------------+-----+
产品
+---------------+-----+---------------+-------+
| productid | id | id_category | price |
+---------------+-----+---------------+-------+
| Product1 | 1 | 1 | 10 |
| Product2 | 2 | 2 | 12 |
+---------------+-----+---------------+-------+
REVIEW
+---------------+-----------+---------------+
| reviewid | idProduct | Score |
+---------------+-----------+---------------+
| 1 | 1 | 10 |
| 2 | 1 | 9 |
+---------------+-----------+---------------+
SALE
+---------------+------------+
| idsale | idproduct |
+---------------+------------+
| sale1 | 1 |
| sale2 | 1 |
+---------------+------------+
我想要什么
+---------------+--------+-----------------+---------+
| category | sales | average score | Reviews |
+---------------+--------+-----------------+---------+
| category1 | 2 | 9.5 | 2 |
| category2 | 0 | | |
+---------------+--------+-----------------+---------+