假设我有一个名为“REVIEWS”的表
此表包含客户为各种产品撰写的评论。
我希望能够对每个客户撰写的所有评论进行“计数”, 所以我写道:
SELECT count(*) AS counter
FROM reviews
WHERE customers_id = 12345
现在,我的问题是我希望有一个像上面这样的计数但仅限于已经编写过SPECIFIC产品评论的客户
例如,
SELECT customers_review
FROM reviews
WHERE
products_id = '170'
总之,我希望能够为他们撰写的每篇评论获得客户总计数,但仅限于为特定产品撰写评论的客户。
非常感谢你的帮助。
答案 0 :(得分:8)
select customers_id, count(*)
from reviews
where customers_id in
(select customers_id from reviews where products_id = '170')
group by customers_id;
答案 1 :(得分:3)
SELECT customers_id, COUNT(*) AS counter
FROM reviews
WHERE customers_id IN(
SELECT customers_id
FROM reviews
WHERE
products_id = '170'
)
GROUP BY customers_id
这将吸引任何撰写产品X的客户,然后计算他们发布的评论总数。
答案 2 :(得分:1)
只需添加到第一个查询的末尾
WHERE EXISTS ( SELECT 1 FROM reviews AS r WHERE r.customers_id = reviews.customers_id AND product_id = '170') GROUP BY reviews.customers_id
答案 3 :(得分:1)
Select customer_ID, Count(*)
FROM reviews
WHERE customer_ID in ( Select Customer_ID from reviews where products_id = '170')
Group By customer_ID
这应该为您提供所有CustomerID的列表以及所有评论的Count,但它仅限于已经对产品170进行评审的客户。
答案 4 :(得分:0)
不同意此主题中的方法。但我认为窗口/分析SQL提供了另一种查看此问题的方法。你可以得到计数:
SQL声明
SELECT
revid,
CUSTID,
PRODID,
COUNT (*) OVER (PARTITION BY custid) ByCust,
COUNT (*) OVER (PARTITION BY prodid) ByProd,
COUNT (*) OVER (PARTITION BY prodid, custid) ByCustProd
FROM customer_reviews
ORDER BY custid, prodid
<强> - 输出 - 强>
1520 106 1900 16 604 3
4650 106 1900 16 604 3
2730 106 1900 16 604 3
4640 106 3900 16 254 1
6287 110 1900 28 604 2
5849 110 1900 28 604 2
5965 110 3900 28 254 2
6117 110 3900 28 254 2