SQL 选择其中仅包含特定值的行
我有一个这样的表,
Col 1 Col 2 Col 3
1 A 1
2 A 2
3 B 1
4 C 1
5 C 2
6 D 1
如何仅获取 Col 3 = 1 的唯一行?
我想要获取第 3 行和第 6 行(第 2 列分别 = B 和 D)。我不想要 A 或 C,因为它们也有 Col 3 = 2。
我尝试过以下方法:
select col 2 from table group by col 2having count(col 3) = 1
但这只会显示 Col 2 的结果,所以我不确定 Col 是否3 内容 = 1 或否。
编辑:抱歉,也许我没有清楚地表达我的问题。我想要获取第 2 列中仅包含第 3 = 1 且仅 1 的所有行。
因此,如果我尝试 WHERE Col 3= 1
,它将返回 4 行,因为 A 有 1 行。但由于 A 也有一行 Col 3 = 2,所以我不希望这样,C 也是如此。从这个示例表中,我希望最终结果只显示 2 行,B 和 D。
我的示例表只是一个示例,我实际上有大约 5000 行要过滤,否则我会按照你们的建议进行操作:)
I have a table as such
Col 1 Col 2 Col 3
1 A 1
2 A 2
3 B 1
4 C 1
5 C 2
6 D 1
How do I only get unique rows which have Col 3 = 1?
I want to get rows 3 and 6 (Col 2 = B and D respectively). I do not want A nor C since they have Col 3 = 2 as well.
I've tried something along the lines of:
select col 2 from table group by col 2 having count(col 3) = 1
But that only brings up Col 2 for results so I'm uncertain if Col 3 contents = 1 or not.
EDIT: Sorry guys maybe I've not worded my question clearly. I want to get all of the rows of Col 2 which contain only Col 3 = 1 AND ONLY 1.
So if I tried WHERE Col 3= 1
, it would return 4 rows because A has 1. But since A also has a row where Col 3 = 2, I do not want that, same for C. From this example table, I would want the end result to only show 2 rows, B and D.
My example table is an example, I actually have about 5000 rows to filter through, otherwise I'd do as you guys have suggested :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或者
Or
您可能正在寻找的是 WHERE 条款。
What you are probably looking for is WHERE clause.
确切地知道你想要得到什么有点困难,但这是我最好的猜测:
It's a bit hard to know exactly what you're trying to get, but this is my best guess:
使用 MS SQL2008 和以下内容进行了测试(因此,如果我的答案不正确,可能会阻止其他人测试他们的答案......):
tested with MS SQL2008 and the following (so if my answer is not the correct one it may halp others test theirs...):