根据列值从 mysql 结果中过滤重复项
我在解决如何从以下 mysql 表返回所需行时遇到一些问题:
first_name last_name collection
==========================================
Bob Jones 1
Ted Jones 1
Bob Jones 1
Bob Jones 2
Ted Baker 2
我想根据列“first_name”和“last_name”返回名称计数。通常,这只是使用“按名字、姓氏分组”的简单情况,因此我们将得到以下结果:鲍勃·琼斯 (Bob Jones) 计数为 3,泰德·琼斯 (Ted Jones) 计数为 1,泰德·贝克 (Ted Baker) 计数为 1。
不过,难点在于第三栏“收藏”。我需要排除集合之间的重复名称,但不需要排除集合内的重复名称。因此,我们将在第一个集合的计数中包含所有名称,但仅在第二个集合的计数中包含名称(如果这些名称未出现在第一个集合中)。
因此,期望的结果如下:Bob Jones 计数为 2,Ted Jones 计数为 1,Ted Baker 计数为 1。
first_name last_name collection included?
========================================== ===============
Bob Jones 1 Yes
Ted Jones 1 Yes
Bob Jones 1 Yes
Bob Jones 2 No
Ted Baker 2 Yes
我确实尝试过解决这个问题,但我开始没有想法了。任何帮助将不胜感激...谢谢!
I'm having some problems working out how to return the desired rows from the following mysql table:
first_name last_name collection
==========================================
Bob Jones 1
Ted Jones 1
Bob Jones 1
Bob Jones 2
Ted Baker 2
I want to return the count of names based on columns 'first_name' and 'last_name'. Ordinarily it would just be a simple case of using 'group by first_name, last_name', so we would have the following result: a count of 3 for Bob Jones, 1 for Ted Jones, and 1 for Ted Baker.
However, the difficulty is the third column 'collection'. I need to exclude duplicate names between collections, but not within collections. So we'd include all names in the count for the first collection, but only include names in the count from the second collection if they do NOT occur in the first collection.
So, the desired result would be as follows: a count of 2 for Bob Jones, 1 for Ted Jones, and 1 for Ted Baker.
first_name last_name collection included?
========================================== ===============
Bob Jones 1 Yes
Ted Jones 1 Yes
Bob Jones 1 Yes
Bob Jones 2 No
Ted Baker 2 Yes
I have really tried to get my head around this but I am starting to run out of ideas. Any help would be hugely appreciated... thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许
COUNT DISTINCT 会消除重复的 Bob/Jones/1 记录。
Perhaps
The COUNT DISTINCT would eliminate the duplicate Bob/Jones/1 records.
这是你所期待的吗?
http://www.sqlfiddle.com/#!2/bd086/7
Is this what you are expecting?
http://www.sqlfiddle.com/#!2/bd086/7