SQL - 设置差异并获取不属于差异一部分的字段
我有一个基本上执行类似以下操作的查询:
select a, b, c
from tab
where tab.state = 'A'
minus
select a, b, c
from tab
where tab.state = 'B'
在此示例中,a
、b
和 c
是该表的关键字段。 state
也是键的一部分,我正在尝试查找状态 A 中有记录而不是状态 B 的情况。还有另一个字段(不在键中)我我想报告值
,不同州的同一条记录可能会有所不同。示例:
a b c state value --------------------- 1 1 1 A 12 1 2 2 A 1002 1 3 9 A 43 1 1 1 B 17.34 1 2 2 B 1002
在本例中,我对键为 1,3,9
且状态为 A 的行感兴趣。我还想获取 value
的值code> 列,但如果我尝试:
select a, b, c, value
from tab
where tab.state = 'A'
minus
select a, b, c, value
from tab
where tab.state = 'B'
我会返回两行:
a b c value ---------------- 1 1 1 12 1 3 9 43
基本上,我希望结果集中有 value
,但不参与 minus
。我觉得我在这里错过了一些明显的东西,但也许我只是太累了而无法得到它......;)
I have a query that basically performs something like this:
select a, b, c
from tab
where tab.state = 'A'
minus
select a, b, c
from tab
where tab.state = 'B'
In this example, a
, b
, and c
are the key fields of this table. state
is also a part of the key, and I'm trying to find situations where there is a record in state A and not in state B. There is another field (not in the key) that I'd like to report on, value
, that might be different for the same record in different states. Example:
a b c state value --------------------- 1 1 1 A 12 1 2 2 A 1002 1 3 9 A 43 1 1 1 B 17.34 1 2 2 B 1002
In this case, I'm interested in the row whose key is 1,3,9
where state is A. I'd also like to get the value of the value
column, but if I try:
select a, b, c, value
from tab
where tab.state = 'A'
minus
select a, b, c, value
from tab
where tab.state = 'B'
What I would get returned is two rows:
a b c value ---------------- 1 1 1 12 1 3 9 43
Basically, I want to have value
in the result set, but not participate in the minus
. I feel like I'm missing something obvious here, but maybe I'm just too tired to get it... ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行此操作的明显方法如下:
如果数据可以有双精度,我什至会在外部查询中添加一个
distinct
。The obvious way to do this is like this:
I would even add a
distinct
in the outer query if the data can have doubles.您可以将
state = 'A'
的所有行与state = 'B'
的匹配行连接起来......然后选择没有的行匹配:
You can join all rows where
state = 'A'
with the matching ones withstate = 'B'
......and then pick the rows where there were no match:
我相信上面的代码可以解决问题。
I believe above code would do the trick.