如何使用 TOP 1 信息和来自 Top 1 信息的排序依据选择不同的信息
我有 2 个表,看起来像:
CustomerInfo(CustomterID, CustomerName)
CustomerReviews(ReviewID, CustomerID, Review, Score)
我想搜索评论中的字符串并返回 CustomerInfo.CustomerID
和 CustomerInfo.CustomerName
。但是,我只想显示不同的 CustomerID
和 CustomerName
以及它们的 CustomerReviews.Reviews
和 CustomerReviews.Score
之一代码>.我还想通过 CustomerReviews.Score
进行订购。
我不知道如何做到这一点,因为客户可以留下多条评论,但我只想要一份评分最高的客户列表。
有什么想法吗?
I have 2 tables, that look like:
CustomerInfo(CustomterID, CustomerName)
CustomerReviews(ReviewID, CustomerID, Review, Score)
I want to search reviews for a string and return CustomerInfo.CustomerID
and CustomerInfo.CustomerName
. However, I only want to show distinct CustomerID
and CustomerName
along with just one of their CustomerReviews.Reviews
and CustomerReviews.Score
. I also want to order by the CustomerReviews.Score
.
I can't figure out how to do this, since a customer can leave multiple reviews, but I only want a list of customers with their highest scored review.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是每组中最大的问题,在 Stack Overflow 上已经出现了数十次。
这是一个与窗口函数配合使用的解决方案:
这是一个更广泛地与不支持窗口函数的 RDBMS 品牌配合使用的解决方案:
我正在展示
CONTAINS()
函数,因为您应该使用 SQL Server 中的全文搜索工具,而不是使用LIKE
带有通配符。This is the greatest-n-per-group problem that has come up dozens of times on Stack Overflow.
Here's a solution that works with a window function:
And here's a solution that works more broadly with RDBMS brands that don't support window functions:
I'm showing the
CONTAINS()
function because you should be using the fulltext search facility in SQL Server, not usingLIKE
with wildcards.我投票支持比尔·卡文的答案,但我想我应该放弃另一个选择。
它使用 相关子查询,对于大数据集经常会出现性能问题,所以要谨慎使用。我认为唯一的好处是查询更容易立即理解。
我没有添加字符串搜索过滤器,但可以轻松添加。
I voted for Bill Karwin's answer, but I thought I'd throw out another option.
It uses a correlated subquery, which can often incur performance problems with large data sets, so use with caution. I think the only upside is that the query is easier to immediately understand.
I didn't add the string search filter, but that can be easily added.
我认为这应该可以做到
I think this should do it