SQL查询在两个列中搜索一个值,并从另一列及其计数获取值
表中有两个列: col_left
和 col_right
。
我需要选择所有行,其中 foo
发生的所有行都发生在这两个列中的任何一个中,并生成两列:
列,其其他值在同一行上使用
foo
IE来自另一列的值(col_left
或col_right
)列,该列发生了许多其他值
但我不确定如何构建整个查询。
我正在使用SQL Server LocalDB数据库。
这是它应该如何工作的示例:
非常感谢。
There are two columns in the table: COL_LEFT
and COL_RIGHT
.
I need to select all rows where value of FOO
occurs in either of these two columns and generate two columns:
Column with the other value that is on the same row with
FOO
ie value from the other column (COL_LEFT
orCOL_RIGHT
)Column with a number of occurences of that other value
I am guessing there would be GROUP BY in the query but I am not sure how to construct the whole query.
I am using SQL Server LocalDB database.
Here is the example of how it should work:
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的解决方案将是以下内容。
但是我认为,最有效的解决方案将要么以下两个:
这将需要两个单独的索引,列的顺序相反。
如您所见,从
A simple solution would be the following.
But I think the most efficient solution would either of the following two:
This would need two separate indexes, with the columns in opposite order, to be performant.
As you can see from this fiddle, the second and third execution plans have no sorts or hash matches, whereas the first requires a sort.
认为您可以使用:
[左]
或[右]
是'foo'的过滤记录。[left]
列中放置不是“ foo”的值。[左]
列和计数。示例SQL小提琴
Thinking that you can do with:
[LEFT]
or[RIGHT]
is 'Foo'.[LEFT]
column.[LEFT]
column and count.Sample SQL Fiddle